How to set specific property value of all objects in a JavaScript object array?

Sometimes, we want to set specific property value of all objects in a JavaScript object array.

In this article, we’ll look at how to set specific property value of all objects in a JavaScript object array.

How to set specific property value of all objects in a JavaScript object array?

To set specific property value of all objects in a JavaScript object array, we can use the array map method.

For instance, we write:

const arr = [{
    id: "a1",
    guid: "sdfsfd",
    value: "abc",
  },
  {
    id: "a2",
    guid: "sdfsfd",
    value: "def",
  },
  {
    id: "a2",
    guid: "sdfsfd",
    value: "def",
  },

]
const newArr = arr.map(e => ({
  ...e,
  status: "active"
}));
console.log(newArr)

to call arr.map with a function that returns an object with the entry e spread into a new object.

And then we add the status property to the same object.

Therefore, newArr is

[{
  guid: "sdfsfd",
  id: "a1",
  status: "active",
  value: "abc"
}, {
  guid: "sdfsfd",
  id: "a2",
  status: "active",
  value: "def"
}, {
  guid: "sdfsfd",
  id: "a2",
  status: "active",
  value: "def"
}]

Conclusion

To set specific property value of all objects in a JavaScript object array, we can use the array map method.