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

Sep 30, 2024

When working with arrays in JavaScript, you may encounter the need to add an object to an array. The push method is commonly used to achieve this. Here's how to push an object into an array in JavaScript.

1. Creating an array:

First, you need to create an array that will hold the objects. You can do this by using the array literal notation or the Array constructor function.

```javascript

// Using array literal notation

let myArray = [];

// Using Array constructor function

let myArray = new Array();

```

2. Creating an object:

Next, you need to create an object that you want to add to the array. You can define the object with the desired properties and values.

```javascript

let myObject = {

key1: 'value1',

key2: 'value2',

// ...more key-value pairs

};

```

3. Pushing the object into the array:

Once you have the array and the object, you can use the push method to add the object to the end of the array.

```javascript

myArray.push(myObject);

```

Now, the object has been pushed into the array and you can access it at the last index of the array.

4. Example:

Here's a complete example of pushing an object into an array:

```javascript

let myArray = [];

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

let obj2 = { name: 'Jane', age: 30 };

myArray.push(obj1);

myArray.push(obj2);

console.log(myArray);

// Output: [ { name: 'John', age: 25 }, { name: 'Jane', age: 30 } ]

```

It's important to note that the push method modifies the original array and returns the new length of the array. This means that the original array is updated with the new object.

In conclusion, pushing an object into an array in JavaScript is a common operation that can be easily achieved using the push method. By following the steps outlined above, you can successfully add objects to arrays in your JavaScript applications.

Recommend