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.
var users = [
{ username: 'x', password: 'secret', email: 'x@x.com' }
, { username: 'y', password: 'secret2', email: 'y@x.com' }
];
users.push( { username: 'z', password: 'secret3', email: 'z@x.com' } )
You could also just set users[users.length] = the_new_element
but I don't think that looks as good.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.