Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of objects by multiple properties and values

Tags:

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?

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

like image 838
BarryWalsh Avatar asked Jun 02 '17 14:06

BarryWalsh


2 Answers

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)
like image 178
Sandeep Nayak Avatar answered Oct 04 '22 19:10

Sandeep Nayak


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);
like image 26
Nenad Vracar Avatar answered Oct 04 '22 21:10

Nenad Vracar