admin管理员组文章数量:1379510
I have a JavaScript data structure like the following in my Node.js/Express web app:
var users = [
{ username: 'x', password: 'secret', email: '[email protected]' }
, { username: 'y', password: 'secret2', email: '[email protected]' }
];
After receiving posted form values for a new user:
{
req.body.username='z',
req.body.password='secret3',
req.body.email='[email protected]'
}
I'd like to add the new user to the data structure which should result in the following structure:
users = [
{ username: 'x', password: 'secret', email: '[email protected]' }
, { username: 'y', password: 'secret2', email: '[email protected]' }
, { username: 'z', password: 'secret3', email: '[email protected]' }
];
How do I add a new record to my users array using the posted values?
I have a JavaScript data structure like the following in my Node.js/Express web app:
var users = [
{ username: 'x', password: 'secret', email: '[email protected]' }
, { username: 'y', password: 'secret2', email: '[email protected]' }
];
After receiving posted form values for a new user:
{
req.body.username='z',
req.body.password='secret3',
req.body.email='[email protected]'
}
I'd like to add the new user to the data structure which should result in the following structure:
users = [
{ username: 'x', password: 'secret', email: '[email protected]' }
, { username: 'y', password: 'secret2', email: '[email protected]' }
, { username: 'z', password: 'secret3', email: '[email protected]' }
];
How do I add a new record to my users array using the posted values?
Share Improve this question edited Jun 22, 2012 at 18:24 jbabey 46.7k12 gold badges72 silver badges94 bronze badges asked Jun 22, 2012 at 18:13 Mike HeffelfingerMike Heffelfinger 4151 gold badge10 silver badges19 bronze badges2 Answers
Reset to default 6You can use the push method to add elements to the end of an array.
var users = [
{ username: 'x', password: 'secret', email: '[email protected]' }
, { username: 'y', password: 'secret2', email: '[email protected]' }
];
users.push( { username: 'z', password: 'secret3', email: '[email protected]' } )
You could also just set users[users.length] = the_new_element
but I don't think that looks as good.
You can add items to an array in many ways:
Push - adds to the end (think stack)
Unshift - adds to the beginning (think queue)
Splice - generic (push and unshift are wrappers around this)
本文标签: nodejsHow do I add a new complex entry to a javascript arrayStack Overflow
版权声明:本文标题:node.js - How do I add a new complex entry to a javascript array? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744450058a2606699.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论