Push an Object to an Array in JavaScript
In JavaScript, you can add items to an array in a number of ways, like initializing the array with an item, pushing an item into the array, combining arrays, etc.
Here we'll see how you can push a JavaScript object into an array.
To achieve this, we'll use the push
method.
let array = [];
let obj = {
name: 'Billy',
age: 30,
role: 'admin'
};
array.push(obj);
console.log(array);
// [{name: 'Billy', age: 30, role: 'admin'}]
As you can see, we simply pass the obj
object to the push()
method and it will add it to the end of the array.
To add multiple objects to an array, you can pass multiple objects as arguments to the push()
method, which will add all of the items to the end of the array.
let array = [];
let obj = {
name: 'Billy',
age: 30,
role: 'admin'
};
let obj2 = {
name: 'Timmy',
age: 25,
role: 'user'
};
array.push(obj, obj2);
console.log(array);
// [{name: 'Billy', age: 30, role: 'admin'}, {name: 'Joe', age: 25, role: 'user'}]
You can also achieve the same thing by passing the object directly to the push()
method, without first assigning it to a variable.
let array = [];
array.push({
name: 'Billy',
age: 30,
role: 'admin'
});
console.log(array);
// [{name: 'Billy', age: 30, role: 'admin'}]
Another method, although less common, is to use the concat()
method. This method is used to combine two arrays, which can also be used to simply add an object to an array.
In this example we use concat()
to add two objects to the array, although you could add any number of objects.
let array = [];
let obj = {
name: 'Billy',
age: 30,
role: 'admin'
};
let obj2 = {
name: 'Timmy',
age: 25,
role: 'user'
};
array = array.concat(obj, obj2);
console.log(array);
// [{name: 'Billy', age: 30, role: 'admin'}, {name: 'Joe', age: 25, role: 'user'}]
Notice that we have to assign the result of the call back to the array since a new array is returned.