Categories
JavaScript Answers

How to change value of object which is inside an array using JavaScript?

Spread the love

To change value of object which is inside an array using JavaScript, we use findIndex to find the item.

For instance, we write

const myArray = [
  { id: 0, name: "John" },
  { id: 1, name: "Sara" },
  { id: 2, name: "Domnic" },
  { id: 3, name: "Bravo" },
];

const objIndex = myArray.findIndex((obj) => obj.id == 1);
myArray[objIndex].name = "Bob";

to call findIndex to find index of the object in myArray with id 1.

Then we use the index to get the item from myArray and assign its name property to 'Bob'.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.