Add property to each object in an array of object in JavaScript


Add property to each object in an array of object in JavaScript

In this post, we will see how to add a property to an object in an array of objects using JavaScript.

In JavaScript, we can add a property to an object using the dot notation or the bracket notation like this:

//dot notation
Objectname.propertyname = value


//bracket notation
Objectname['propertyname'] = value

Example:

let person = {name:'John'}

person.address = 'New York'

console.log(person) // { name: 'John', address: 'New York' }

Here, we have used the dot notation to add the address property to the person object.

Now to add a property to an object in an array of objects we can use :

  1. forEach() method, or

  2. map() method

Let's check each with an example.

Add a Property to Each Object in an Array of Objects using forEach

We can use the forEach method to loop through all the objects in the array and add the new property to it.

For Example, suppose we have a list of person object in an array.

const personArr = [{name:'John'}, {name:'Tom'}, {name:'David'}]

personArr.forEach((element) => {
  element.city = 'New York'

});
console.log(personArr)

Output:

[
  { name: 'John', city: 'New York' },
  { name: 'Tom', city: 'New York' },
  { name: 'David', city: 'New York' }
]

In the above example, we have an array of objects with name property and we have looped through each object in the array with forEach() method and added the city property to it using dot notation.

Add Property in an Array of Objects using the map method

We can also add a property to an object in an array of objects using the map method in JavaScript.

The map() method creates a new array by calling a function on each element in the given array.

const personArr = [{name:'John'}, {name:'Tom'}, {name:'David'}]

const newArr = personArr.map(element => ({
 ...element, city : 'Chicago'
}))

console.log(newArr)

Output:

[
  { name: 'John', city: 'Chicago' },
  { name: 'Tom', city: 'Chicago' },
  { name: 'David', city: 'Chicago' }
]

In the above example, we have used the map() method with a callback function on each object of the array.

Inside the callback, we have used the spread operator (...) on each element object and added the city property to each object.


Related Topics:

Use Array forEach() to loop through JavaScript object

JavaScript - Iterate over the properties of an object

How to remove a property from an object in JavaScript

How to Remove Object from Array in JavaScript?