Sometimes, we want to modify object property in an array of objects with JavaScript.
In this article, we’ll look at how to modify object property in an array of objects with JavaScript.
How to modify object property in an array of objects with JavaScript?
To modify object property in an array of objects with JavaScript, we can use the array find
method.
For instance, we write
const foo = [
{ bar: 1, baz: [1, 2, 3] },
{ bar: 2, baz: [4, 5, 6] },
];
const obj = foo.find((f) => f.bar == 1);
if (obj) {
obj.baz = [2, 3, 4];
}
console.log(foo);
to define the foo
array.
Then we call foo.find
with a callback to return the object in foo
with bar
set to 1.
If obj
isn’t undefined
, then we set obj.baz
to a new value.
Conclusion
To modify object property in an array of objects with JavaScript, we can use the array find
method.