根据值列表过滤对象数组
2021-03-25
72
我有一个如下的数组
array = [
{
name: 'A'
instructors: [
{
name:'InsA'
}
]
businessUnit: {name:'myBusiness'}
},
{
name: 'B'
instructors: [
{
name:'InsB'
}
]
businessUnit: {name:'myBusinessB'}
}
]
我想用我拥有的值过滤这个数组,这些值也在下面的数组中
nameArr = [A,C,D]
instructorArr = [InsA,InsC,InsZ]
businessName = [myBusinessB,myBusinessX,myBusinessD]
如果我只需要检查一个值,是否可以过滤这个数组,如下所示
const filtered = _.filter(groupActivityList, (obj) => {
return (
obj.name === (groupClassFilter !== defaultFilter ? groupClassFilter : obj.name) &&
obj.instructors.length > 0 &&
obj.instructors[0]?.name ===
(groupInstructorFilter !== defaultFilter
? groupInstructorFilter
: obj.instructors.length > 0 && obj.instructors[0]?.name) &&
obj.businessUnit.name ===
(groupFacilityFilter !== defaultFilter ? groupFacilityFilter : obj.businessUnit.name)
);
});
当我有一组要过滤的值时,如何过滤,例如:
nameArr = [A,C,D]
2个回答
使用
Array.prototype.some
和
Array.prototype.includes
过滤数组的示例:
const array = [{
name: 'A',
instructors: [{
name: 'InsA'
}],
businessUnit: {
name: 'myBusinessA'
}
},
{
name: 'B',
instructors: [{
name: 'InsB'
}],
businessUnit: {
name: 'myBusinessB'
}
},
{
name: 'Z',
instructors: [{
name: 'InsZZ'
}],
businessUnit: {
name: 'myBusinessZZ'
}
}
];
const nameArr = ['A', 'C', 'D']
const instructorArr = ['InsA', 'InsC', 'InsZ']
const businessName = ['myBusinessB', 'myBusinessX', 'myBusinessD', 'myBusinessA']
const filtered = array.filter(el => nameArr.includes(el.name) && el.instructors.some(ins => instructorArr.some(iA => ins.name === iA)) &&
businessName.includes(el.businessUnit.name)
);
console.log(filtered);
Ramesh Reddy
2021-03-25
如果我正确理解了这个问题,您可以使用 Array#some 属性。
除了检查
obj.name === filterObj.name
,您还可以使用
fiterObj.names.some(name => name === obj.name)
进行检查,如果
namesArr
中的任何元素与对象的名称匹配,它将返回 true
Sinan Yaman
2021-03-25