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

If you are looking to add an object to an array in JavaScript, the push() method is the way to go. This method allows you to easily append new items to the end of an array. When it comes to objects, you can push an entire object into an array as a new element. Here's how you can do it:

1. Create an empty array:

```

let myArray = [];

```

2. Create an object:

```

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

```

3. Push the object into the array:

```

myArray.push(myObject);

```

By executing the above code, the object 'myObject' will be added to the end of the 'myArray' as a new element. You can also add multiple objects to the array by calling the push() method multiple times with different objects.

It's important to note that when you push an object into an array, you're not creating a reference to the original object. Instead, a new element with the same properties and values as the original object is created within the array.

Here's a practical example of pushing objects into an array:

```

let users = [];

let user1 = { name: 'Alice', age: 30 };

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

users.push(user1);

users.push(user2);

console.log(users); // Output: [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 28 }]

```

In this example, the objects 'user1' and 'user2' are both added to the 'users' array using the push() method, resulting in an array of user objects.

In summary, the push() method in JavaScript is a simple and effective way to add objects to an array. It allows you to easily append new elements, including objects, to the end of an array. Whether you're working with a single object or multiple objects, the push() method can help you efficiently manage and manipulate arrays in your JavaScript applications.

Recommend