Advertisements
How to Add an Object to an Array in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the push()
Method
You can simply use the Array push()
method to add an object to an array in JavaScript.
Let's try out the following example to understand how it basically works:
Example
Try this code »// Sample array
var persons = ["Peter", "Clark", "John"];
// Sample object
var obj = {name: "Harry", age: 18};
// Adding object to the array
persons.push(obj);
console.log(persons);
Related FAQ
Here are some more FAQ related to this topic:
- How to check if object is an array in JavaScript
- How to check if an array includes an object in JavaScript
- How to find an object by property value in an array of JavaScript objects
Advertisements