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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.