JavaScript Add Property To Array

JavaScript Add Property To Array | Array & Objects are the most important data types in not only JavaScript but in any programming language. These data types can be nested and an array of objects can be created. 

In this article, we will discuss how to add a property to the JavaScript Array of Objects. An array of objects may look like the following:-

const arr = [{
    a: 'foo',
},
{
    a: 'bar',
},
{
    a: 'baz',
}];

The above array is named ‘arr’ which contains three objects with one property each. To add a property to all objects in the array there are two methods. The method is as follows:-

  1. forEach() Method
  2. map() Method

JavaScript Add Property To Array Using forEach() Method

The forEach() method mutates which means it changes the original array. It can be used to loop through every object in an array, and the desired property can be added to the objects. To add a property we can declare it as we would do in a normal object. The following example shows how to use the forEach method:-

Program in JavaScript to add a property to an array using the forEach() Method

const arr = [{
    a: 'foo',
},
{
    a: 'bar',
},
{
    a: 'baz',
}];

// add property
arr.forEach(obj => {
    obj.b = 'pan'
});

// display array
console.log(arr);

Output:-

[
{ a: ‘foo’, b: ‘pan’ },
{ a: ‘bar’, b: ‘pan’ },
{ a: ‘baz’, b: ‘pan’ }
]

JavaScript Add Property To All Objects In Array Using map() Method

The map function requires a callback function as an argument. It returns a new array instead of making changes to the same one. The required change in the object should be returned in the callback function. A spread operator can be used to spread and edit existing objects. Example usage of the map method is as follows:-

JavaScript Add Property To Object In Array Using map() Method

const arr = [{
    a: 'foo',
},
{
    a: 'bar',
},
{
    a: 'baz',
}];

// add property
const arr2 = arr.map(obj => (
    {...obj, b:'pan'}
));

// display array
console.log(arr2);

Output:-

[
{ a: ‘foo’, b: ‘pan’ },
{ a: ‘bar’, b: ‘pan’ },
{ a: ‘baz’, b: ‘pan’ }
]

In both methods, we loop over each object in a Javascript array. These methods can be used to add a property or multiple properties to an array of objects in JavaScript. 

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *