W3jar
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:

  1. Initialize an array: myArray is an empty array.
  2. Create an object: myObject is an object with properties name and age.
  3. Push the object: The push method is used to add myObject to the end of myArray.

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.