Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Push Object into an Array in JavaScript

Oct 11, 2024

In JavaScript, you can push objects into an array using the built-in push() method. This method adds one or more elements to the end of an array and returns the new length of the array. To push an object into an array, you can simply call the push() method on the array and pass the object as an argument. Here's an example:

```javascript

let array = [{ name: 'John', age: 25 }, { name: 'Jane', age: 30 }];

let newObj = { name: 'Bob', age: 28 };

array.push(newObj);

console.log(array);

```

In this example, we have an array of objects `array` containing two objects. We then create a new object `newObj` and push it into the `array` using the push() method. The resulting array will now contain three objects, including the new object we pushed.

If you want to push multiple objects into the array at once, you can do so by passing multiple arguments to the push() method. Here's an example:

```javascript

let array = [{ name: 'John', age: 25 }, { name: 'Jane', age: 30 }];

let newObjs = [{ name: 'Bob', age: 28 }, { name: 'Alice', age: 22 }];

array.push(...newObjs);

console.log(array);

```

In this example, we use the spread syntax `...` to expand the `newObjs` array into individual elements and push them into the `array`. This allows us to push multiple objects into the array in a single statement.

It's important to note that when you push an object into an array, you are actually pushing a reference to the object, not a copy of the object itself. This means that if you modify the object after pushing it into the array, the changes will be reflected in the array as well. If you want to avoid this and create a copy of the object, you can use the spread syntax to create a new object before pushing it into the array.

In conclusion, pushing objects into an array in JavaScript is a straightforward task using the push() method. Whether you're adding a single object or multiple objects, the push() method allows you to efficiently update and manage arrays of objects in your JavaScript applications.

Recommend