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

If you want to add an object to an array in JavaScript, you can use the push method. To do this, first, create an object with the desired key-value pairs. Then, use the push method to append the object to the end of the array. Here's an example:

```javascript

let array = []; // create an empty array

let obj = {key1: 'value1', key2: 'value2'}; // create an object

array.push(obj); // add the object to the array

console.log(array); // output: [{key1: 'value1', key2: 'value2'}]

```

In this example, we first create an empty array called 'array' and an object called 'obj' with key-value pairs. We then use the push method to add the 'obj' to the end of the 'array'. When we log the 'array' to the console, we can see that the 'obj' has been successfully added to the array.

It's important to note that the push method modifies the original array and returns the new length of the array. If you want to add multiple objects to an array, you can simply call the push method multiple times with different objects.

In addition to using the push method, you can also use the spread operator to add an object to an array. Here's an example:

```javascript

let array = []; // create an empty array

let obj = {key1: 'value1', key2: 'value2'}; // create an object

array = [...array, obj]; // add the object to the array

console.log(array); // output: [{key1: 'value1', key2: 'value2'}]

```

In this example, we use the spread operator to create a new array that includes all the elements from the original 'array' as well as the 'obj'. We then reassign this new array to the original 'array'.

In conclusion, adding an object to an array in JavaScript is simple and can be done using the push method or the spread operator. Both methods allow you to easily add objects to arrays, making it convenient to work with collections of data in JavaScript.

Recommend