How to Update an Object in useState Array By Index in JavaScript

How can we update an object in an array stored in our component state in JavaScript?

Suppose we’re working in React.js or Next.js, and we have an array stored in our component state.

const [users, setUsers] = useState([]);

First, we need to know how to get a subarray from an array in JavaScript.

Get subarray from array in JavaScript

Suppose we have an array arr with 4 elements.

If we want to get the middle 2 elements in the array, we can use slice().

const arr = [1,2,3,4];
const subarr = arr.slice(1,3); // [2,3]

The first argument is the start index, inclusive.

The second argument is the stop index, exclusive.

This means that slice(1,3) is obtaining the array over indexes [1,3).

Update object in state array by index

Finally, we can update an object in a state array using this slice() function as well as the spread operator.

const updateUser = (key, value, index) => {
  const user = users[index];
  user[key] = value;
    ...users.slice(0, index),
    ...users.slice(index + 1, users.length)

We’re keeping all the values up to, but not including, the index.

Then, we’re keeping all the values from index + 1 to the end of the array.

In between both of those, we’ll squeeze in the updated object.

Feel free to read about how to add elements to a useState array and delete elements in a useState array.