How to Edit the Value in a Nested Array in React

Kamille Longalong
1 min readMar 27, 2021
Photo by Nataliya Vaitkevich from Pexels

I was doing my React project and I needed to edit the value of just one object inside a nested array. I didn’t know what to do at first.

I encountered this issue when I was doing my final project with Flatiron. I want to share how I was able to do this.

Step 1:

Find the index in the array. For me, I used the id to find the object I was looking for.

const index = state.notebooks.findIndex(notebook => notebook.id === action.payload.notebook_id)

Step 2:

Create a copy of the array using the spread operator.

const updatedNotebooks = […state.notebooks]

Step 3:

Redefine the object that needs to be updated. I used the bracket notation for its index. Then create a copy of the object and rewrite the specific value of the key. I did this on my reducer so I used action.payload.

updatedNotebooks[index] = {...updatedNotebooks[index], notes: [...updatedNotebooks[index].notes, action.payload]}

Step 4:

Return the updated array.

return {
notebooks: updatedNotebooks
}

--

--