Updating a value in a nested array of objects

How to update just one value in an array of objects in a state

Sylwia Vargas
Feb 3 · 2 min read
“Red and Blue Pelikan Br 40 Eraser on White Surface” by Pixabay

Say we have a component with an array of to-do’s, just like this:

state = {
todos: [
{id: 1,
title: "Eat breakfast",
completed: false},
{id: 2,
title: "Make bed",
completed: false}
]
}

How could we change the value of just key in just one object?

Step 1: Find the element

We first want to find the index in the array of the object, or where the object is located in the array. You can find the element by any key, id or name, or any other you find useful. We will use its id that e.g. we are getting from the function . Find the given element by its id and its (e.g. by using the method .findIndex())

const elementsIndex = this.state.todos.findIndex(element => element.id == id )

Step 2: Create a copy of the state array

Because we should never modify directly the state, let’s create its copy through ES6 spread operator feature and let’s save it to a variable.

let newArray = [...this.state.todos]

Step 3: Update the one value

Here are our steps:
1. Let’s redefine the one object we want to update using bracket notation for its index.
2. Let’s create the copy of the object (spread operator again) and then rewrite the one value of the one key we want. In this case, we will switch the “completed” key from false to true and so we are using the ! to negate the current value.

newArray[elementsIndex] = {...newArray[elementsIndex], completed: !newArray[elementsIndex].completed}

Note: While ‘todos’ is an array and that’s why the index matters, the individual toDoItem is an object and objects are unordered collections. Because of that, you can choose just one value out of order that will get updated.

Step 4: SetState

Pass newArr as a value of ‘todos’:

this.setState({
todos: newArray,
});

JavaScript in Plain English

Learn the web's most important programming language.

Sylwia Vargas

Written by

accessible tech && social justice | I teach React,JavaScript, Ruby, Rails at Flatiron School | Follow me: https://twitter.com/sylwiavargas

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade