Modelo

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

How to Add Object to Array in JavaScript

Oct 01, 2024

Adding an object to an array in JavaScript is a common task in web development. There are several ways to achieve this, but one of the most straightforward methods is to use the push method. The push method is a built-in JavaScript function that allows you to add one or more elements to the end of an array. Here's an example of how to use the push method to add an object to an array:

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

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

myArray.push(newObj);

console.log(myArray);

In this example, we have an array called myArray that contains two objects. We then create a new object called newObj. We use the push method to add newObj to the end of myArray. When we log myArray to the console, we can see that newObj 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.

Another method for adding an object to an array is by using the spread operator. The spread operator allows you to add elements from one array to another. Here's an example of how to use the spread operator to add an object to an array:

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

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

myArray = [...myArray, newObj];

console.log(myArray);

In this example, we use the spread operator to create a new array that contains all the elements from myArray, as well as newObj. When we log myArray to the console, we can see that newObj has been added to the array.

In conclusion, adding an object to an array in JavaScript is a fundamental task that can be achieved using the push method or the spread operator. Both methods are effective and have their own advantages. Whether you choose to use the push method or the spread operator, you can easily add objects to an array and manipulate the data in your JavaScript applications.

Recommend