我正在尝试从嵌套对象中删除一项。名为“类别”的对象,其中包含多个类别,每个类别都有多个业务。类似于波纹管对象:
let categories = [{
name: 'Home',
biz: [{
name: 'Business 1',
id: 50
}, {
name: 'Business 2',
id: 52
}, {
name: 'Business n',
id: 53
}]
}, {
name: 'Car',
biz: [{
name: 'Business 1',
id: 62
}, {
name: 'Business 2',
id: 66
}, {
name: 'Business n',
id: 67
}]
}];
我要做的是删除用户选择的其中一项业务,并返回整个对象而不更改原始状态。
到目前为止,我做了类似波纹管的事情,但它工作正常,但是我不确定我是用正确的方法还是错误的方法进行操作。如果您能通过查看或重构此代码来帮助我,我将不胜感激:
categories.map((cat, inedx) => {
return { ...cat, biz: [...cat.biz.filter(bz => bz.id!== 66)]}
});
答案 0 :(得分:1)
减少营救:-)
const fn = (categories, id) => {
return categories.reduce((r, x) => {
return r.concat({ ...x, biz: x.biz.filter(x => x.id !== id) });
}, []);
}
console.log(fn(categories, 66));
答案 1 :(得分:0)
let categories = [{
name: 'Home',
biz: [{
name: 'Business 1',
id: 50
}, {
name: 'Business 2',
id: 52
}, {
name: 'Business n',
id: 53
}]
}, {
name: 'Car',
biz: [{
name: 'Business 1',
id: 62
}, {
name: 'Business 2',
id: 66
}, {
name: 'Business n',
id: 67
}]
}];
categories.forEach(el => el.biz = el.biz.filter(e => e.id !== 66));
console.log("removed biz 66", categories)