[英]Underscore.js: filter objects with nested array of objs
I am trying to filter top-level objects based on nested data (filtering is also needed for nested objects).我正在尝试根据嵌套数据过滤顶级对象(嵌套对象也需要过滤)。
Filter params: All records with categoryValue A.过滤参数:categoryValue A 的所有记录。
const table = [
{
name: 'Bob',
detail: [
{ category: 'Employeer', categoryValue: 'A' },
{ category: 'Employeer', categoryValue: 'B' },
],
},
{
name: 'Alice',
detail: [
{ category: 'Employeer', categoryValue: 'C' },
{ category: 'Employeer', categoryValue: 'D' },
],
},
];
I am expecting the following result我期待以下结果
const fileredTable = [
{
//this
name: 'Bob',
detail: [
//and only this
{ category: 'Employeer', categoryValue: 'A' }
],
}
];
Ok, after several tries i found this solution:好的,经过几次尝试,我找到了这个解决方案:
const filteredTable = table.flatMap((item) => {
const filteredDetail = item.detail.filter((e) => e.categoryValue === 'A')
return filteredDetail.length !== 0 ? {...item, detail: filteredDetail} : []
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.