How to Add Object to Array in JavaScript
The simplest way an object or any other type of element can be added to a JavaScript array is indexing. You can just assign the object to an index of the array and if there is an item already present there then it will be replaced by the new object:
let arr = [{"Name": "Richard Roe", "id": 1}, {"Name": "John Smith", "id": 2}];
arr[2] = obj;
console.log(arr);
This method is quite easy but it’s hard to know the indices and size of the arrays so we have to look for some other methods which can be used to add objects to arrays. The most well-known, convenient and easy to use methods are push(), unshift() and splice(). Their functionalities are slightly different but any of these methods can be used. Let’s take a look at how these are different:
array.push() Method
The array.push() method takes elements as parameters and adds them to the end of the array and returns the new size of the array:
let arr = [{"Name": "Richard Roe", "id": 1}, {"Name": "John Smith", "id": 2}];
arr.push(obj);
console.log(arr);
array.unshift() Method
The array.unshift() function is the opposite of the push method as it adds elements to the beginning of the array. Similar to the push method it can take one or more elements as parameters and add them to an array:
let arr = [{"Name": "John Smith", "id": 2}, {"Name": "John Doe", "id": 3}];
arr.unshift(obj);
console.log(arr);
array.splice() Method
The array.splice() method is a bit different as it can be used to both delete and insert elements from a given index. It takes three arguments, the index, no of elements to delete and the new element which is to be added:
let arr = [{"Name": "Richard Roe", "id": 1}, {"Name": "John Smith", "id": 2}];
arr.splice(2, 0, obj)
console.log(arr);
We have given 0 as the 2nd parameter as we don’t want to delete any elements from the existing array.
Additional Useful Methods
JavaScript also offers a lot of other useful methods for manipulating arrays, objects and objects present within arrays. The array.apply() and the array.concat() are two of such functions which might be helpful in our case.
The array.apply() method can be used to combine the contents of arrays. So, if you have two different arrays which contain objects and you want to add the objects of one array to another, you do not have to do it manually one by one. You can just use the apply() method. Moreover, if you need a new array to be formed from the contents of the existing array then you can use the concat() function.
Conclusion
The push, unshift and splice methods can be used to add objects to JavaScript arrays. The push method adds objects to the end, the unshift method adds objects to the start and the splice method adds them at a given index of the array. All of these methods have been extensively explained in the guide above.