Reputation: 3439
I use filter to find all the items in a nested array. But then I would like to change the "quantity" of all the found items. The same item can be found in multiple categories and subcategories.
It would be nice if I could modify it like this, but it is not working...
let item_id = 681
let new_quantity = 10
categories.flatMap(category => category.subcategories.flatMap(subcategory => subcategory.items))
.filter(item => item.id == item_id)
.item.quantity = new_quantity
Here is my categories > subcategories > items array (I want to change quantity from 5 to 10 where item_id = 681)
[
{
id: 1,
description: 'First category',
subcategories: [
{
id: 1,
description: 'First subcategory',
items: [
{
id: 681,
description: 'House',
quantity: 5,
}
]
}
]
},
{
id: 2,
description: 'Second category',
subcategories: [
{
id: 1,
description: 'First subcategory',
items: [
{
id: 681,
description: 'House',
quantity: 5,
}
]
}
]
},
]
Upvotes: 0
Views: 2278
Reputation: 1701
If the depth of the nested categories is variabel (e.g. you habe sub-sub-categories), then this might be helpful also:
let categories = [{id:1,description:"First category",subcategories:[{id:1,description:"First subcategory",items:[{id:681,description:"House",quantity:5}]}]},{id:2,description:"Second category",subcategories:[{id:1,description:"First subcategory",items:[{id:681,description:"House",quantity:5}]}]}];
let item_id = 681
let new_quantity = 10
function eachRecursive(obj, cb) {
for (var k in obj) {
cb(k, obj);
if (typeof obj[k] == "object" && obj[k] !== null)
eachRecursive(obj[k], cb);
}
}
eachRecursive(categories, (key, obj) => {
if(key === 'items') {
let itemIndex = obj[key].findIndex(item => item.id === item_id);
obj[key][itemIndex].quantity = new_quantity;
}
});
console.log(categories);
Upvotes: 0
Reputation: 1794
Use map
instead.
categories.flatMap(category => category.subcategories.flatMap(subcategory => subcategory.items))
.map(item =>{
if(item.id == item_id){
item.quantity = new_quantity;
}
return item;
})
Upvotes: 1