I'm trying to remove an item from a nested object. object named "categories" that contains several categories and each category has several businesses. something like bellow object:
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
}]
}];
What I'm trying to do is removing one of this businesses that selected by user and return the whole object without mutating original state.
so far I did something like bellow and it's working fine bu I'm not sure if I'm doing this the right way or the wrong way. I appreciate if you guys help me by review or refactor this code:
categories.map((cat, inedx) => {
return { ...cat, biz: [...cat.biz.filter(bz => bz.id!== 66)]}
});
reduce to the rescue :-)
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));
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)
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.