Modelo

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

How to Push an Object into an Array in JavaScript

Oct 20, 2024

Pushing an object into an array in JavaScript is a common operation that can be performed using the push method. The push 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 and pass the object as an argument. Here's an example of how to do this:

```javascript

let myArray = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}];

let newObj = {id: 3, name: 'Tom'};

myArray.push(newObj);

```

In this example, we have an array `myArray` containing two objects, and we want to push a new object `newObj` into the array. We simply call the `push` method on `myArray` and pass `newObj` as an argument. After this operation, `myArray` will contain three objects, including the newly pushed object.

It's important to note that when you push an object into an array, you are actually adding a reference to the object, not a copy of the object itself. This means that if you modify the original object after pushing it into the array, the changes will also be reflected in the array.

If you want to make a copy of the object and push the copy into the array, you can use the spread operator or the `Object.assign()` method. Here's an example using the spread operator:

```javascript

let myArray = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}];

let newObj = {id: 3, name: 'Tom'};

myArray.push({...newObj});

```

In this example, we use the spread operator `{...newObj}` to create a new object with the same properties and values as `newObj`, and then we push this new object into the array.

In summary, pushing an object into an array in JavaScript is a straightforward operation that can be achieved using the `push` method. Keep in mind the difference between pushing a reference to the object and pushing a copy of the object, and choose the method that best suits your needs.

Recommend