Categories
JavaScript Answers

How to Add a Property to Each Object in an Array of Objects with JavaScript?

Spread the love

Sometimes, we want to add a property to each object in an array of JavaScript objects.

In this article, we’ll look at how to add a property to each object in an array of JavaScript objects.

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

We can use the forEach method to loop through each element in an object and add a property to each.

For instance, we can write:

const arr = [{
  a: 'foo'
}, {
  a: 'bar'
}, {
  a: 'baz'
}]
arr.forEach((element) => {
  element.b = 'qux'
});
console.log(arr)

We have the arr array.

Then we call forEach with a callback that has the element parameter with the object being iterated through and we assign the b property to a value.

Therefore, arr is:

[
  {
    "a": "foo",
    "b": "qux"
  },
  {
    "a": "bar",
    "b": "qux"
  },
  {
    "a": "baz",
    "b": "qux"
  }
]

according to the console log.

Add a Property to Each Object in an Array of Objects with JavaScript with map

Also, we can use the map method to do the same thing.

For instance, we can write:

const arr = [{
  a: 'foo'
}, {
  a: 'bar'
}, {
  a: 'baz'
}]
const mapped = arr.map((element) => ({
  ...element,
  b: 'qux'
}));
console.log(mapped)

We call map with a callback where we spread the element object and add a b property to the same object.

And mapped is:

[
  {
    "a": "foo",
    "b": "qux"
  },
  {
    "a": "bar",
    "b": "qux"
  },
  {
    "a": "baz",
    "b": "qux"
  }
]

according to the console log.

Conclusion

We can use the forEach method to loop through each element in an object and add a property to each.

Also, we can use the map method to do the same thing.

Leave a Reply

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