187 words
1 minutes
How to Push an Object to an Array in JavaScript
To push an object to an array in JavaScript, you use the push
method. Here’s a basic example to illustrate this:
// Initialize an array
let myArray = [];
// Create an object
let myObject = {
name: "Alice",
age: 30,
};
// Push the object to the array
myArray.push(myObject);
// Verify the array now contains the object
console.log(myArray);
In this example:
- Initialize an array:
myArray
is an empty array. - Create an object:
myObject
is an object with propertiesname
andage
. - Push the object: The
push
method is used to addmyObject
to the end ofmyArray
.
If you want to push multiple objects to the array at once, you can do so by calling push
with multiple arguments:
// Initialize an array
let myArray = [];
// Create objects
let object1 = { name: "Alice", age: 30 };
let object2 = { name: "Bob", age: 25 };
// Push multiple objects to the array
myArray.push(object1, object2);
// Verify the array now contains both objects
console.log(myArray);
Here, both object1
and object2
are added to myArray
in a single push
call.
The push
method modifies the original array and returns the new length of the array.