0

let's say i have arrays with useState in React. In this arrays i have objects

const [myArray, setMyArray] = useState([
  { id: 1, name: "Butter", pieces: 4},
  { id: 2, name: "Bread", pieces: 2}
])

const [myArray2, setMyArray2] = useState([
  { id: 1, name: "Butter", pieces: 4},
  { id: 2, name: "Bread", pieces: 2}
])

on the UI i have the ability to move this items from myArray from a container to the next container where the Items of myArray2 are inside

when i move the 2 pieces of the butter from myArray to the Container where the Items of myArray2 are, it should filter for Butter in myAarray2 and if it found the butter it should update the pieces of the founded Butter in myArray2 with the 2 pieces that i moved so at the that at the end the array should like this

const [myArray, setMyArray] = useState([
  { id: 1, name: "Butter", pieces: 2},
  { id: 2, name: "Bread", pieces: 2}
])

const [myArray2, setMyArray2] = useState([
  { id: 1, name: "Butter", pieces: 6},
  { id: 2, name: "Bread", pieces: 2}
])

i only can't figure out how to make the filter function for finding the Butter in myArray2 and update it with 4 + 2 so that there are 6 pieces then

i know it should be like that:

 const itemthathastobeupdated = myArray2.filter((item) => item.name == props.name);

would be great if someone can help me out here

MisterLA
  • 91
  • 1
  • 8
  • try using `reduce`, after you filter. – BARNOWL Oct 08 '20 at 18:27
  • Does this answer your question? [Whats the best way to update an object in an array in ReactJS?](https://stackoverflow.com/questions/28121272/whats-the-best-way-to-update-an-object-in-an-array-in-reactjs) – Emile Bergeron Oct 08 '20 at 18:31
  • not completly because i do not want to search by index.It should realy search by the id because i'm getting the array objects from my backend normaly and sometimes there is a id: 83 and this would not be the same with the index so it can be like {id: 83, name: "bread", pieces: 4}, {id: 92, name: "butter", pieces: 8}. At the end it the id would not be instantly also the index. – MisterLA Oct 08 '20 at 18:52

0 Answers0