EN
JavaScript - find and update values in array of objects
0
points
In this article, we would like to show you how to find and update values in an array of objects in JavaScript.
1. Using findIndex()
method
In this example, we use findIndex()
method to get the index
of an element with the same id
as the replacement.id
and update the element with the replacement
object.
// ONLINE-RUNNER:browser;
const array = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
];
const replacement = { id: 3, name: 'd' };
const index = array.findIndex((x) => x.id === replacement.id);
array[index] = replacement;
console.log(JSON.stringify(array));
Note:
This solution will update only the first occurrence of an object with given id (
id: 3
).
2. Using forEach()
method
In this example, we use forEach()
method to loop through the array
and update all elements whose id
is equal to the replacement.id
with the replacement
object.
// ONLINE-RUNNER:browser;
const array = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 3, name: 'c' },
];
const replacement = { id: 3, name: 'd' };
array.forEach((element, index) => {
if (element.id === replacement.id) {
array[index] = replacement;
}
});
console.log(JSON.stringify(array));
Note:
This solution will update all occurrences of objects with given id (
id: 3
).