How to Add Property to Array of Objects in JavaScript

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

Method 1: Using Array.prototype.map()

Array.prototype.map() function is used to iterate over each element in the array and apply the callback function to each element. The callback function is expected to return a new element, which is used to create a new array.

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

Here is a code 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() to iterate over each object within the array.

Add a new property directly to the object during each iteration. This approach modifies the original array, adding a new property to each object.

Here is a code 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.