How to Push an Object to an Array in JavaScript
Table of Contents
Arrays of objects in JavaScript is a powerful feature because of how much information you can store all in one variable.
In this post, we're going to learn how you can push an object to an array in JavaScript.
Pushing an object to an array
When you have an an array of objects and want to push another object to the end of the array, you can use the push()
method.
This method takes the object as a parameter and adds it at the end of the array.
First, let's define our array:
JAVASCRIPTlet array = [
{
name: 'John',
age: 30
},
{
name: 'Jane',
age: 28
}
];
Now the object we want to push:
JAVASCRIPTconst object = {
name: 'Bob',
age: 25
};
Now we can push it and print it:
JAVASCRIPTarray.push(object);
console.log(array);
Here's the full example:
JAVASCRIPTlet array = [
{
name: 'John',
age: 30
},
{
name: 'Jane',
age: 28
}
];
const object = {
name: 'Bob',
age: 25
};
array.push(object);
console.log(array);
The output is:
JAVASCRIPT0: {name: 'John', age: 30}
1: {name: 'Jane', age: 28}
2: {name: 'Bob', age: 25}
As expected, our new object is added to the end of the array, making the entire array have a length of 3
.
Conclusion
In this post, we looked at how to push an object to an array in JavaScript.
You just need to call the push()
method on the array and pass in the object you want to push to the end.
Hopefully, you've found this helpful. Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- Git Tutorial: Learn how to use Version Control
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Using Axios to Pull Data from a REST API