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: "123",
value: "abc",
},
{
id: "a2",
guid: "123",
value: "def",
},
{
id: "a2",
guid: "123",
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: "123",
id: "a1",
status: "active",
value: "abc"
}, {
guid: "123",
id: "a2",
status: "active",
value: "def"
}, {
guid: "123",
id: "a2",
status: "active",
value: "def"
}]