How to Push an Object to an Array in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 10 20211 min read

banner

Photo by Greg Raines

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

In the code snippet we used the Array.push method to push an object into the array.

The object gets pushed to the end of the array.

If you only had the values that the object should contain, you must create the object, before pushing 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 assign one or more key-value pairs in the object and once the values are assigned we use the push method to add the object to the end of the array.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee