Javascript 按多个属性和值过滤对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44330952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:27:48  来源:igfitidea点击:

Filter array of objects by multiple properties and values

javascriptfilter

提问by BarryWalsh

Is it possible to filter an array of objects by multiple values?

是否可以通过多个值过滤对象数组?

E.g in the sample below can I filter it by the term_ids 5 and 6 and type car at the same time?

例如,在下面的示例中,我可以通过 term_ids 5 和 6 过滤它并同时输入 car 吗?

[  
   {  
      "id":1,
      "term_id":5,
      "type":"car"
   },
   {  
      "id":2,
      "term_id":3,
      "type":"bike"
   },
   {  
      "id":3,
      "term_id":6,
      "type":"car"
   }
]

Definitely up for using a library if it makes it easier.

绝对可以使用库,如果它更容易的话。

回答by Sandeep Nayak

You can do it with Array.filter

你可以用Array.filter

var data = [{
    "id": 1,
    "term_id": 5,
    "type": "car"
  },
  {
    "id": 2,
    "term_id": 3,
    "type": "bike"
  },
  {
    "id": 3,
    "term_id": 6,
    "type": "car"
  }
];

var result = data.filter(function(v, i) {
  return ((v["term_id"] == 5 || v["term_id"] == 6) && v.type == "car");
})

console.log(result)

回答by Nenad Vracar

You can do this with plain js filter()method and use &&to test for both conditions.

您可以使用普通的 jsfilter()方法执行此操作,并用于&&测试这两种情况。

var data = [{"id":1,"term_id":5,"type":"car"},{"id":2,"term_id":3,"type":"bike"},{"id":3,"term_id":6,"type":"car"}];

var result = data.filter(function(e) {
  return [5, 6].includes(e.term_id) && e.type == 'car'
});

console.log(result);

回答by Abhay Shiro

The following function will help you out.

以下功能将帮助您。

    nestedFilter = (targetArray, filters) => {
          var filterKeys = Object.keys(filters);
          return targetArray.filter(function (eachObj) {
            return filterKeys.every(function (eachKey) {
              if (!filters[eachKey].length) {
                return true; 
              }
              return filters[eachKey].includes(eachObj[eachKey]);
           });
       });
    };

Use this function with filters described as below:

将此函数与如下所述的过滤器一起使用:

var filters = {
    "id": ["3"],
    "term_id": ["6"],
    "type": ["car","bike"]
}

Dont pass empty array. If there are no values in the array, skip that property in the filters.

不要传递空数组。如果数组中没有值,则在过滤器中跳过该属性。

The result will be filtered array.

结果将被过滤数组。