My question relates to this one but the issue here that I must relay on object properties and I want to update just ONE object. If I am using map
it updates all objects in my array of objects. Its structure is:
[
{
id: 1,
itemNames: ['aaa','xxx'],
removed: [],
...
},
{
id: 1,
itemNames: ['yyy', 'xxx'],
removed: [],
...
},
...
]
My logic is: I look for item name across itemNames, if it exists in state - remove it from first object occurance and add it to removed property of this object. I managed to do it with map, but then it does it for every object that has given item name.
function filterByItemName(itemName) {
this.setState(prevState => ({
...prevState,
arr: prevState.arr.map(item) => {
if (item.itemNames.includes(itemName)) {
return {
...item,
removed: [...item.removed, itemName],
itemNames: removeFirstFoundElement(item.itemNames, itemName),
};
}
return item;
}),
}));
}
The following code works in a way that it finds ALL objects with given itemName - but I would like to change just first case... After calling filterByItemName('xxx')
I want it to be:
[
{
id: 1,
itemNames: ['aaa'],
removed: ['xxx],
...
},
{
id: 1,
itemNames: ['yyy', 'xxx'],
removed: [],
...
},
...
]
While now it is as follows:
[
{
id: 1,
itemNames: ['aaa'],
removed: ['xxx],
...
},
{
id: 1,
itemNames: ['yyy'],
removed: ['xxx'],
...
},
...
]
I think you can set a shouldInsert
flag to check if you've already inserted once or not. Here is my approach. It would be easier if you could share some codesandbox
link here.
function filterByItemName(itemName) {
let shouldInsert = true;
this.setState(prevState => ({
...prevState,
arr: prevState.arr.map(item) => {
const found = item.itemNames.includes(itemName);
if (found && shouldInsert) {
shouldInsert = false;
return {
...item,
removed: [...item.removed, itemName],
itemNames: removeFirstFoundElement(item.itemNames, itemName),
};
}
return item;
}),
}));
}
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.