I have a JavaScript data structure like the following in my Node.js/Express web app:
var users = [
{ username: 'x', password: 'secret', email: 'x@x.com' }
, { username: 'y', password: 'secret2', email: 'y@x.com' }
];
After receiving posted form values for a new user:
{
req.body.username='z',
req.body.password='secret3',
req.body.email='z@x.com'
}
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: 'x@x.com' }
, { username: 'y', password: 'secret2', email: 'y@x.com' }
, { username: 'z', password: 'secret3', email: 'z@x.com' }
];
How do I add a new record to my users array using the posted values?
You can use the push method to add elements to the end of an array.
You could also just set
users[users.length] = the_new_elementbut I don’t think that looks as good.