How to Push an Object to an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Push an Object to an Array in JavaScript #

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr.push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.

index.js
let arr = []; const obj = {name: 'Tom'}; arr.push(obj); console.log(arr); // 👉️ [{name: 'Tom'}]

We used the Array.push method to push an object into an array.

The object gets pushed to the end of the array.

If you only have the values that the object should contain, create the object before pushing it into the array.

index.js
let arr = []; const obj = {}; const name = 'Tom'; obj['name'] = name; arr.push(obj); console.log(arr); // 👉️ [{name: 'Tom'}]

We can use bracket notation to add one or more key-value pairs to the object.

Once the key-value pairs are assigned to the object, use the push method to add the object to the end of the array.

The same approach can be used to push multiple objects to an array.

index.js
const arr = []; const obj1 = {name: 'Alice'}; const obj2 = {name: 'Bob'}; const obj3 = {name: 'Carl'}; arr.push(obj1, obj2, obj3); // 👇️ [{name: 'Alice'}, {name: 'Bob'}, {name: 'Carl'}] console.log(arr);

The Array.push() method takes one or more values and pushes them to the array.

This enables us to pass multiple, comma-separated objects as arguments in the call to push().

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.