如何按条件对象数组过滤对象数组。
接口:
interface Person {
age: number;
available: boolean;
}
interface PersonFilter {
predicateFn(arg: Person): boolean;
}
数据:
const persons = [
{
"age": 2,
"available": false
},
{
"age": 5,
"available": true
}
];
过滤条件:
const filters = [
{predicateFn: person => person.available},
{predicateFn: people => person.age > 2}
];
如何使用当前过滤器结构过滤此对象数组?
function getFilteredPersons(filters): Person[]{
return persons.filter( ?? );
}
预期产出:
[
{
"age": 5,
"available": true
}
]
答案 0 :(得分:2)
您可以使用Array.prototype.every
函数进行尝试,它类似于:
const persons = [{
age: 2,
available: false
},
{
age: 5,
available: true
}
];
const filters = [{
predicateFn: person => person.available
},
{
predicateFn: person => person.age > 2
}
];
function getFilteredPersons(filters) {
return persons.filter(p => filters.every(filter => filter.predicateFn(p)));
}
console.log(getFilteredPersons(filters));