How to Push an Object to an Array in JavaScript

To push an object to an array in JavaScript, call the push() method on the array with the object as an argument, i.e., arr.push(obj). The push() method will add the element to the end of the array.

For example:

const arr = [];

const obj = { name: 'Jeff' };

// 👇 Push object to array
arr.push(obj);

// [{ name: 'Jeff' } ]
console.log(arr);

The push() method takes an object and adds it to the end of an array.

Push object to array during initialization

If the variable is newly created just before the object is pushed (like in the previous example), you can simply place the object in between the square brackets ([]) to include it in the array as the variable is initialized:

const obj = { name: 'Jeff' };

// 👇 Push object to array with initialization
const arr = [obj];

console.log(arr);

Push multiple objects to array

The push() method actually accepts a variable number of arguments. They are each added to the end of the array, in the order in which they are passed to push().

For example:

const arr = [];

const obj1 = { name: 'Samantha' };
const obj2 = { name: 'Chris' };
const obj3 = { name: 'Mike' };

arr.push(obj1, obj2, obj3);

// [ { name: 'Samantha' }, { name: 'Chris' }, { name: 'Mike' } ]
console.log(arr);

Push object to array without mutation

The push() method adds an object to the array in place, which means it gets modified. If you don’t want this, you can use the spread syntax (...) to create a copy of the original array, before calling push():

const arr = [{ name: 'Jerry' }];

const newArr = [...arr];

newArr.push({ name: 'Mia' });

// [ { name: 'Jerry' }, { name: 'Mia' } ]
console.log(newArr);

// 👇 Original not modified
console.log(arr); // [ { name: 'Jerry' } ]

Similar to what we did earlier, we can include the object in the square brackets, after the spread syntax, to push the object to the array’s copy as it is initialized:

const arr = [{ name: 'Jerry' }];

// 👇 Push object to array without mutation
const newArr = [...arr, { name: 'Mia' }];

// [ { name: 'Jerry' }, { name: 'Mia' } ]
console.log(newArr);

// Original not modified
console.log(arr); // [ { name: 'Jerry' } ]

While not always necessary, by avoiding mutations we can make our code more readable, predictable, and modular.



11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *