我有一个对象数组:
const myArr = [{
name: 'a',
age: 23,
nationality: 'swedish',
},
{
name: 'b',
age: 23,
nationality: 'swedish',
},
{
name: 'c',
age: 25,
nationality: 'spanish',
},
];
我要使用以下参数进行过滤:
const myQuery = {
name: 'a',
nationality: 'swedish'
}
如何为多个动态参数构建过滤器?我可能正在寻找“姓名”,“年龄”,“国籍”或其他类似“已婚”的
答案 0 :(得分:3)
我使用Object.keys获取myQuery的键,然后用.find过滤myArr
如果发现某些内容,我将返回undefined,并且对象返回True。
如果找不到对象,则会得到布尔变量,并且对象返回False。
const myArr = [{
name: 'a',
age: 23,
nationality: 'swedish',
},
{
name: 'b',
age: 23,
nationality: 'swedish',
},
{
name: 'c',
age: 25,
nationality: 'spanish',
},
];
const myQuery = {
nationality: 'swedish'
}
const filterArray = (arr, query) => {
return arr.filter(rec => {
return (typeof Object.keys(query)
.find(key => rec[key] !== query[key]) === 'undefined')
})
}
console.log(filterArray(myArr, {nationality: 'swedish'}))
console.log(filterArray(myArr,{name: 'a',nationality: 'swedish'}))
console.log(filterArray(myArr, {name: 'a',nationality: 'spanish'}))