change value of an array react code example
Example 1: update an item in array of object
let myArray = [
{id: 0, name: "Jhon"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"}
],
objIndex = myArray.findIndex((obj => obj.id == 1));
console.log("Before update: ", myArray[objIndex])
myArray[objIndex].name = "Laila"
console.log("After update: ", myArray[objIndex])
Example 2: update object in array state by index
this.setState(({items}) => ({
items: [
...items.slice(0,1),
{
...items[1],
name: 'newName',
},
...items.slice(2)
]
}));