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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

You 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