How to Add Property to Array of Objects in JavaScript

To add a property to an Array of Objects in JavaScript, you can use Array.prototype.map() or Array.prototype.forEach() method.

Method 1: Using the Array.prototype.map() function

The Array.prototype.map() function iterates over each element in the array and applies the callback function to each element. The callback function is expected to return a new element, which is used to create a new array. In this case, you create a new object for each element by spreading the properties of the original object and adding the new property.

This approach does not modify the original array and instead creates a new array with objects that include the new property.

Example

const arrayOfObjects = [
  { id: 1, name: "Niva" },
  { id: 2, name: "Khushi" },
  { id: 3, name: "Millie" }
];

const newArray = arrayOfObjects.map((obj) => {
  return {
    ...obj,
    age: 30
  };
});

console.log(newArray);

Output

[
  { id: 1, name: 'Niva', age: 30 },
  { id: 2, name: 'Khushi', age: 30 },
  { id: 3, name: 'Millie', age: 30 }
]

We created a new array newArray is created, and the objects in the new array have the additional age property. The original arrayOfObjects remains unchanged in this case.

Method 2: Using the Array.prototype.forEach() function

You can use the Array.prototype.forEach() method that iterates over each object within the array. You can add a new property directly to the object during each iteration. This approach modifies the original array, adding a new property to each object.

Example

const arrayOfObjects = [
  { id: 1, name: "Niva" },
  { id: 2, name: "Khushi" },
  { id: 3, name: "Millie" }
];

// Using forEach
arrayOfObjects.forEach((obj) => {
  obj.age = 30;
});

console.log(arrayOfObjects)

Output

[
  { id: 1, name: 'Niva', age: 30 },
  { id: 2, name: 'Khushi', age: 30 },
  { id: 3, name: 'Millie', age: 30 }
]

In this example, the original arrayOfObjects is modified, and each object within the array now has the age property.

Leave a Comment