Categories
JavaScript Answers

How to find and update values in an array of objects in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.