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?
You can add objects of any data type to an array using the push() function. You can also add multiple values to an array by adding them in the push() function separated by a comma. To add the items or objects at the beginning of the array, we can use the unshift() function.
To convert an array's values to object keys:Use the reduce() method to iterate over the array. On each iteration, assign the array element as a key in the accumulator object. The reduce method will construct an object from the array's values.
Use .push:
items.push({'id':5});
.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);
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}].
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}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With