Reputation: 4926
I have an array as :
items=[{'id':1},{'id':2},{'id':3},{'id':4}];
How should I add a new pair {'id':5}
to the array?
Upvotes: 37
Views: 172645
Reputation: 1131
New solution with ES6
Default object
object = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
Another object
object = {'id': 5};
Object assign ES6
resultObject = {...obj, ...newobj};
Result
[{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}];
Upvotes: 2
Reputation: 515
If you're doing jQuery, and you've got a serializeArray thing going on concerning your form data, such as :
var postData = $('#yourform').serializeArray();
// postData (array with objects) :
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, etc]
...and you need to add a key/value to this array with the same structure, for instance when posting to a PHP ajax request then this :
postData.push({"name": "phone", "value": "1234-123456"});
Result:
// postData :
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, {"name":"phone","value":"1234-123456"}]
Upvotes: 2
Reputation: 81
Sometimes .concat() is better than .push() since .concat() returns the new array whereas .push() returns the length of the array.
Therefore, if you are setting a variable equal to the result, use .concat().
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
newArray = items.push({'id':5})
In this case, newArray will return 5 (the length of the array).
newArray = items.concat({'id': 5})
However, here newArray will return [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}].
Upvotes: 7
Reputation: 39322
.push() will add elements to the end of an array.
Use .unshift() if need to add some element to the beginning of array i.e:
items.unshift({'id':5});
Demo:
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.unshift({'id': 0});
console.log(items);
And use .splice() in case you want to add object at a particular index i.e:
items.splice(2, 0, {'id':5});
// ^ Given object will be placed at index 2...
Demo:
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.splice(2, 0, {'id': 2.5});
console.log(items);
Upvotes: 12