How to create a multi-filter function to filter out multiple attributes using JS?

后端 未结 1 588
孤独总比滥情好
孤独总比滥情好 2020-12-11 19:39

Array of objects to be filtered

相关标签:
1条回答
  • 2020-12-11 20:06

    If you format your filter conditions just like an object in your data array, but with values being arrays of possible values, then you can use the filter method as follows:

    let data = [
      {
        "name": "Apple",
        "age": 24,
        "model": "Android",
        "status": "Under development",
      }, {
        "name": "Roboto",
        "age": 24,
        "model": "Apple",
        "status": "Running",
      }, {
        "name": "Samsung",
        "age": 26,
        "model": "Blueberry",
        "status": "Running",
      },
    ];
    
    let filter = {
        "name": ["Roboto", "Ericsson"],
        "age": [22, 24, 26],
    };
    
    let res = data.filter(obj =>
        Object.entries(filter).every(([prop, find]) => find.includes(obj[prop])));
        
    console.log(res);

    0 讨论(0)
提交回复
热议问题