How to Find and Update an Object with an ID in JavaScript?

Estimated read time 1 min read

To find and update an object with an ID in JavaScript, you can use the map method to iterate through an array of objects, find the object with the desired ID, and update its properties.

Here’s an example:

function updateObject(id, updates, arr) {
  return arr.map(function(obj) {
    if (obj.id === id) {
      return Object.assign({}, obj, updates);
    }
    return obj;
  });
}

let arr = [{id: 1, name: "John"}, {id: 2, name: "Jane"}];
let updatedArr = updateObject(2, {name: "Jim"}, arr);
console.log(updatedArr);

In this example, the code defines a function updateObject that takes an id, an object of updates updates, and an array of objects arr as arguments. The function uses the map method to iterate through the arr array and find the object with the desired id. If the object is found, it is updated using the Object.assign method. The Object.assign method creates a new object that is the result of merging the original object and the updates. The updated array is then returned. The code then calls the updateObject function with the arguments 2, {name: "Jim"}, and arr and logs the result to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply