'Can't modify a property of an object in an array after using the filter method
I have 2 arrays of objects (the same): 1 (artificesToAdd[]) which can contain 0 or more objects and the 2nd (newFilter[]) which can also contain 0 to a couple of objects, based on a search performed by a user.
The goal is that for each object contained in the artificesToAdd[] array, I check if this object also exists in the newFilter[] array. If so, I need to update the 'qtyToAdd' property to indicate the quantity that is initially in my first array.
Unfortunately I get this error :
'Uncaught TypeError: Cannot add property qtyToAdd, object is not extensible'
My understanding is that this array can't be modified because it's in reference but I'm not sure about this and I don't know how to resolve it? Should I create another array and push items needed inside?
The error occur on this particular line: newFilter[artIndex].qtyToAdd = item.qty;
const handleFilter = (event: any) => {
const searchWord: string = event.target.value;
const newFilter = artifices.filter((value) => {
return value.codeGF.toUpperCase().includes(searchWord.toUpperCase());
});
// Now let's add ART who had a qty
if (artificesToAdd.length > 0) {
let artIndex: number;
artificesToAdd.forEach(function (item) {
artIndex = newFilter.findIndex((i) => i.id === item.id);
if (artIndex === -1 || artIndex === undefined) return;
console.log(newFilter[artIndex]);
newFilter[artIndex].qtyToAdd = item.qty;
});
}
setFilteredArtifices(newFilter);
};
Solution 1:[1]
This might be a reach, but try changing this: "const newFilter =" to this: "let newFilter="
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeff King |
