Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update a single key value pair in an array of objects in react?

I am trying to update a single key value pair in an array of objets using React.

Here is the setup

An array of objects

const array = [
  {id:1,name:'Tyler',age:23},
  {id:2,name:'Lauren',age:28},
  {id:3,name:'Nico',age:14},
]

Given an id and age, I want to be able to update the single object that matches the id. For example, given an id of 2 and age of 56, {id:2,name:'Lauren',age:28} should change to {id:2,name:'Lauren',age:56}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My approach

I’ve set up useState to copy the array of object. However, I am struggling to filter out for the selected id, change the age, and return the updated array.

This is what I currently have:

import { useState } from "react";

const array = [
  { id: 1, name: "Tyler", age: 23 },
  { id: 2, name: "Lauren", age: 28 },
  { id: 3, name: "Nico", age: 14 }
];

export default function App() {
  const [list, setList] = useState(array);

  const updateAge = (id = 2, age = 56) => {
    setList([...list, list.filter((item) => item.id === id)]);
  };

  return (
    <>
      <ul>
        {list.map((item) => {
          return (
            <li>
              {item.name} | {item.age}
            </li>
          );
        })}
      </ul>
      <button onClick={updateAge}>Update age</button>
    </>
  );
}

Here is my codesandbox link

>Solution :

You can use the map function to produce a new array to set the state with.

const updateAge = (id, age) => {
    console.log(id, age);
    setList(
      list.map((item) => {
        if (item.id === id) {
          return { ...item, age };
        } else {
          return item;
        }
      })
    );
  };

If the id matches, it will merge the new age, otherwise it will return the item unchanged.

Note that it will only produce new objects for updated age, the rest will be the same references. That is to say it will be a new array, but most objects (except the changed one) will be the same. If you want new objects you can return { ...item } in the else clause as well.

In this particular case React will only be concerned that you set the state with new array.

Here’s the sandbox

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading