मैं फ़िल्टर में संग्रहीत मानों के आधार पर अपने 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)
    });
  });
});
}
3
Krishna 4 अप्रैल 2018, 17:35

3 जवाब

सबसे बढ़िया उत्तर

आप प्रत्येक फ़िल्टर की जांच कर सकते हैं और उस ऑब्जेक्ट को वापस कर सकते हैं जो सभी शर्तों से मेल खाता है।

यह दृष्टिकोण शर्तों की मनमानी गिनती के लिए काम करता है।

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; }
5
Nina Scholz 4 अप्रैल 2018, 15:10

एक विकल्प 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; }
5
Ele 4 अप्रैल 2018, 15:13

आप 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);
2
Eddie 4 अप्रैल 2018, 14:41