简体   繁体   English

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

[英]Filter array of objects by multiple properties and values

Is it possible to filter an array of objects by multiple values?是否可以通过多个值过滤对象数组?

Eg 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.绝对可以使用库,如果它更容易的话。

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)

You can do this with plain js filter() method and use && to test for both conditions.您可以使用普通的 js 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(e) { return [5, 6].includes(e.term_id) && e.type == 'car' }); console.log(result);

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.结果将被过滤数组。

Another way to do it is to use lodash filter + reduce.另一种方法是使用 lodash filter + reduce。

 const arr = [{"id":1,"term_id":5,"type":"car"},{"id":2,"term_id":3,"type":"bike"},{"id":3,"term_id":6,"type":"car"}]; const result = [ {term_id: 5, type: 'car'}, {term_id: 6, type: 'car'}, ].reduce((prev, orCondition) => prev.concat(_.filter(arr, orCondition)), []); console.log(result);
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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