how to update an object in an array in javascript

To update an object in an array in JavaScript, you can use the map() function. The map() function creates a new array with the same length as the original array, and it allows you to modify each element of the array using a callback function.

Here's an example:

index.tsx
let myArray = [
  { id: 1, name: 'John', age: 30 },
  { id: 2, name: 'Jane', age: 25 },
  { id: 3, name: 'Bob', age: 40 }
];

// Find the object you want to update
let updatedObject = myArray.find(obj => obj.id === 2);

// Update the object
updatedObject.name = 'Janet';
updatedObject.age = 28;

// Map the array and replace the updated object
let newArray = myArray.map(obj => obj.id === 2 ? updatedObject : obj);

// newArray should now contain the updated object
console.log(newArray);
489 chars
19 lines

In this example, we first find the object with an id of 2 using the find() function. We then update the name and age properties of the object.

Next, we use the map() function to create a new array where we replace the original object with the updated object. We do this by using a ternary operator in the callback function to check if the id of the current object matches the id of the updated object. If it does, we return the updated object. Otherwise, we return the original object.

Finally, we log the new array to the console to confirm that the update was successful.

gistlibby LogSnag