简体   繁体   中英

Typescript filter an array of objects

I want to filter my results array based on the values stored in filters. I have tried the below code. But it is not applying.

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)
    });
  });
});
}

An alternative is using the function filter along with functions includes and 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; } 

You could check for every filter and returns that object which matches all conditions.

This approach works for an arbitrary count of conditions.

 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; } 

You can filter the array and use includes to check if name and city is on the array

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM