简体   繁体   中英

Update object value in useState array of objects

I am currently struggling with changing a couple of states that I currently have in my web app. The state is as follows:

const [points, setPoint] = useState([]);

Which stores the data like this:

0: (2) [{…}, {…}]
1: (2) [{…}, {…}]

In other words, the array contains each an array of two objects. The content looks like this;

0:
elementId: 0
elementPosX: 615
elementPosY: 171
1:
elementId: "liiMJzWgphZPbnx"
elementPosX: 618.5
elementPosY: 317

I want to search if x is equal to the elementId , and then change the values directly linked to this object. How can I achieve this?

I have found a way to edit an object in a regular single array of objects like so:

setPoint(singlePoint.map(x => {
  if (x.id !== id) return x
  return { ...x, position: { x: xPosition - 365, y: yPosition - 80 } }
}))

This works, but I'm not sure if there is an easier way of doing this?

If you care about the array order. You have first to find the element index and then update it:

setPoint((allPoints) => {
  const index = allPoint.findIndex((element) => element.id === x.id);
  allPoints[index] = {
    ...x,
    position: { x: xPosition - 365, y: yPosition - 80 },
  };
  return allPoints;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM