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)