简体   繁体   中英

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?

[  
   {  
      "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

 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.

 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.

 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>

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