简体   繁体   中英

How do I add a new complex entry to a javascript array?

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.

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)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM