How to Push an Object to an Array in JavaScript

Push an Object to an Array in JavaScript

To push an object to an array, use the push() method, passing in the object as a parameter. For example, arr.push({name: 'Matt'}) would add the object to the array. The push method can add one or more elements to the end of an array.

let theArray = [];

const obj = {name: 'Matt'};

theArray.push(obj);

console.log(theArray);
Use the Array.push() method to push an object into an array.
Use the Array.push() method to push an object into an array.

Explanation –

The let theArray = []; line creates an empty array.
The const obj = {name: 'Matt'}; line creates an object with a property called name and a value of ‘Matt’.
The theArray.push(obj); line adds the object to the end of the array.
The console.log(theArray); line prints out the contents of the array, which is just the one object.

The code used the Array.push method to push an object into an array.

The object is pushed to the end of the array.

Only create an object if you have the values that it should contain. Otherwise, push it into the array.

let theArray = [];

const obj = {};
const name = 'Matt';

obj['name'] = name;
arr.push(obj);
console.log(arr);
Bracket notation to add one or more key-value pairs to the object
Bracket notation to add one or more key-value pairs to the object

We can use bracket notation to add new key-value pairs to objects.

ℹ️ Use the push method to add the object, with its key-value pairs, to the end of the array.

You can use the same approach to push multiple objects into an array.

const theArray = [];

const nameOne = {name: 'Matt'};
const nameTne = {name: 'Bob'};
const nameThree = {name: 'Alice'};

theArray.push(nameOne, nameTne, nameThree);

console.log(theArray);
Push multiple objects to an array
Push multiple objects to an array

The Array.push() method pushes one or more values to the end of an array.
This allows us to pass multiple objects as arguments to push(), separated by commas.