Modelo

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

How to Add Objects to an Array in JavaScript

Oct 06, 2024

Adding objects to an array in JavaScript is a common task when working with data. There are two main methods for adding objects to an array: push and unshift. The push method adds one or more elements to the end of an array, while the unshift method adds one or more elements to the beginning of an array.

To add an object to the end of an array using the push method, you can simply call the push method on the array and pass the object as a parameter. For example:

```javascript

let arr = [{name: 'John', age: 30}, {name: 'Jane', age: 25}];

let newObj = {name: 'Jake', age: 28};

arr.push(newObj);

```

In the above example, the newObj object is added to the end of the arr array using the push method.

To add an object to the beginning of an array using the unshift method, you can call the unshift method on the array and pass the object as a parameter. For example:

```javascript

let arr = [{name: 'John', age: 30}, {name: 'Jane', age: 25}];

let newObj = {name: 'Jake', age: 28};

arr.unshift(newObj);

```

In the above example, the newObj object is added to the beginning of the arr array using the unshift method.

It's important to note that the push and unshift methods modify the original array and return the new length of the array. This means that the original array will be changed after calling these methods.

You can also add multiple objects to an array using the push and unshift methods, simply by passing multiple objects as parameters. For example:

```javascript

let arr = [{name: 'John', age: 30}, {name: 'Jane', age: 25}];

let newObj1 = {name: 'Jake', age: 28};

let newObj2 = {name: 'Jill', age: 26};

arr.push(newObj1, newObj2);

```

In the above example, the newObj1 and newObj2 objects are added to the end of the arr array using the push method.

Similarly, you can use the unshift method to add multiple objects to the beginning of an array.

In conclusion, adding objects to an array in JavaScript can be easily accomplished using the push and unshift methods. These methods are essential when working with arrays and are commonly used in a variety of applications.

Recommend