I want to modify an object in an array by calling array.find() and then mutate the returned reference to indirectly mutate the array but that doesnt appear to work. I assumed from reading other articles that array.find() returns a reference to an object in the array on a successful match but that appears not the be the case.
In this codesandbox if I mutate the result from array.find() the array is not updated. I can update the array if I replace array.find() with array.findIndex() and modify the array elements by index, but the code is not as clean and I still dont understand why I cant update by reference.
Does array.find() return a reference to an object in the array or a copy? In the codesandbox provided it appears to behave as though its a copy.
Any advice is appreciated.
CodePudding user response:
Find
just finds the first element in the array, they do not edit the element, but find the element. So when you have the element, you can edit afterward, but you do not have the index of the element inside the array, so you will need the index too if you want to pass the edited element in the array.
You have multiple ways to update. If you want a shorter way, right now it came into my mind like this :
setArray((oldState) =>
oldState.map((item) => {
if (item.value === "one") {
return {
value: "asdasd"
};
}
return {...item};
})
);
So directly you can set the value inside setArray
why? because the map returns a new array.
Or you can write more readable :
const newState = array.map((item) => {
if (item.value === "one") {
return {
value: "asdasd"
};
}
return {...item};
});
setArray(newState)
A similar question can be found here
If you have any questions ask. Thanks.