To find and update values in an array of objects in JavaScript, we use the map
method.
For instance, we write
const updatedData = originalData.map((x) =>
x.id === id ? { ...x, updatedField: 1 } : x
);
to call originalData.map
with a callback that returns the new object if x.id
equals id
and x
otherwise.
An array with the objects returned by the map
callback is returned by map
.