find and update the value inside the object js

Solutions on MaxInterview for find and update the value inside the object js by the best coders in the world

showing results for - "find and update the value inside the object js"
Camilla
02 Aug 2018
1Step1: Inside state
2state = {
3  todos: [
4   {
5     id: 1, 
6    title: "Eat breakfast",
7    completed: false
8   },
9   {
10     id: 2,
11    title: "Make bed",
12    completed: false
13   }
14  ]
15}
16
17Steps: Inside function where you need to update the value
18const elementsIndex = this.state.todos.findIndex(element => element.id == id );
19
20let newArray = [...this.state.todos]
21
22newArray[elementsIndex] = {...newArray[elementsIndex], completed: !newArray[elementsIndex].completed}
23
24this.setState({ todos: newArray });