我使用过滤器来查找嵌套数组中的所有项目。但是,我想更改所有找到的项目的“数量”。同一项目可以在多个类别和子类别中找到。
如果能这样修改它会很好,但是它不起作用...
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
这是我的类别>子类别>项目数组(我想将数量从5更改为10,其中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,
}
]
}
]
},
]
答案 0 :(得分:1)
改为使用map
。
categories.flatMap(category => category.subcategories.flatMap(subcategory => subcategory.items))
.map(item =>{
if(item.id == item_id){
item.quantity = new_quantity;
}
return item;
})
答案 1 :(得分:0)
如果嵌套类别的深度是variabel(例如,您是子类别),那么这也可能会有所帮助:
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);