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 01, 2024

Hey there, JavaScript enthusiasts! Today, we're going to talk about how to push an object into an array in JavaScript. This is a handy skill to have when working with arrays and objects, so let's dive in.

To start, let's create a simple array and an object:

```javascript

let myArray = [];

let myObject = { name: 'John', age: 25 };

```

Now, let's say we want to add this object to our array. We can easily achieve this using the `push` method. Here's how you can do it:

```javascript

myArray.push(myObject);

```

And just like that, our object is now added to the array! You can also add multiple objects to the array using the same `push` method:

```javascript

myArray.push({ name: 'Jane', age: 30 }, { name: 'Bob', age: 22 });

```

Now `myArray` will contain all three objects.

It's important to note that when you push an object into an array, you're actually adding a reference to the object. This means that if you modify the original object, the changes will also be reflected in the array, since it still points to the same object.

If you want to avoid this behavior and create a new independent copy of the object in the array, you can use the `spread` operator or `Object.assign` method:

Using the `spread` operator:

```javascript

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

```

Using the `Object.assign` method:

```javascript

myArray.push(Object.assign({}, myObject));

```

This will create a new copy of the object and add it to the array, leaving the original object unchanged.

So there you have it! You now know how to push objects into an array in JavaScript using the `push` method. This is a powerful technique that you'll find yourself using often in your JavaScript projects. Happy coding!

Recommend