Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new object (key-value pair) to an array in javascript?

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?

like image 461
exAres Avatar asked Sep 23 '13 08:09

exAres


People also ask

How do you add an object to an array 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.

How do you assign an array to an object key?

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.


4 Answers

Use .push:

items.push({'id':5}); 
like image 142
CodingIntrigue Avatar answered Sep 25 '22 01:09

CodingIntrigue


.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);
like image 44
Mohammad Usman Avatar answered Sep 22 '22 01:09

Mohammad Usman


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}].

like image 41
Natorious Avatar answered Sep 23 '22 01:09

Natorious


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}];
like image 36
Ugur Avatar answered Sep 22 '22 01:09

Ugur