我想根据过滤器中存储的值过滤我的results
数组。
我试过下面的代码。但它没有应用。
let filters = {
name: ["Krishna", "Naveen"],
city : ["London"]
};
results = [
{
"name": "Krishna#Surname",
"city": "London",
"age": 23
},
{
"name": "Naveen#Surname",
"city": "London",
"age": 23
},
{
"name": "Krishna#Surname",
"city": "NewYork",
"age": 23
},
{
"name": "Praveen#Surname",
"city": "Washington",
"age": 23
}
]
this.results1 = this.multiFilter(results,filters);
multiFilter(array:any=[], filters:Object) {
const filterKeys = Object.keys(filters);
return array.filter((item) => {
return filterKeys.every(key => {
let filters1= filters[key];
return filters1.every(key1 => {
return !!~ item[key].indexOf(key1)
});
});
});
}
答案 0 :(得分:4)
另一种方法是使用函数filter
以及函数includes
和some
。
let filters = { name: ["Krishna", "Naveen"], city : ["London"]},
results = [{ "name": "Krishna#Surname", "city": "London", "age": 23},{ "name": "Naveen", "city": "London", "age": 23},{ "name": "Krishna", "city": "NewYork", "age": 23},{ "name": "Praveen", "city": "Washington", "age": 23}],
result = results.filter(({name, city}) => filters.name.some(n => name.includes(n)) && filters.city.includes(city));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
您可以检查每个过滤器并返回符合所有条件的对象。
这种方法适用于任意条件。
function multiFilter(array, filters) {
return array.filter(o =>
Object.keys(filters).every(k =>
[].concat(filters[k]).some(v => o[k].includes(v))));
}
var filters = { name: ["Krishna", "Naveen"], city: ["London"] },
results = [{ name: "Krishna#Surname", city: "London", age: 23 }, { name: "Naveen#Surname", city: "London", age: 23 }, { name: "Krishna#Surname", city: "NewYork", age: 23 }, { name: "Praveen#Surname", city: "Washington", age: 23 }],
filtered = multiFilter(results, filters);
console.log(filtered);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)
您可以filter
数组并使用includes
检查名称和城市是否在阵列上
let filters = {name: ["Krishna", "Naveen"],city: ["London"]};
let results = [{"name": "Krishna","city": "London","age": 23},{"name": "Naveen","city": "London","age": 23},{"name": "Krishna","city": "NewYork","age": 23},{"name": "Praveen","city": "Washington","age": 23}]
let result = results.filter(o => filters.name.includes(o.name) && filters.city.includes(o.city));
console.log(result);