Andrea
Andrea

Reputation: 127

How to filter array of object by multiples array/objects values

I need to filter an array of objects, like this:

var models = [
    {
      "family": "Applique",
      "power":"8",
      "volt":"12",
      "color":"4100",
      "type":"E27",
      "ip":"20",
      "dimensions":"230x92"
    },
    {
      "family": "Lanterne",
      "power":"20",
      "volt":"230",
      "color":"2700",
      "type":"R7S",
      "ip":"44",
      "dimensions":"230x92"
    },
    {
      "family": "Applique",
      "power":"50",
      "volt":"230",
      "color":"",
      "type":"GU10",
      "ip":"20",
      "dimensions":"227x227"
    }
]

Based on a object like this:

var filter = {
   "family":[
      "Applique", "Faretto", "Lanterne"
   ],
   "power":{
      "less":[
          "30"
      ],
      "greater":[

      ],
      "equal":[

      ]
   },
   "volt":[
      "12", "230"
   ],
   "color":[

   ],
   "type":[

   ],   
   "ip":[
      "20"
   ]
   "dimensions":[

   ],
}

So, in this case, the result could be:

{
  "family": "Applique",
  "power":"8",
  "volt":"12",
  "color":"4100",
  "type":"E27",
  "ip":"20",
  "dimensions":"230x92"
}

I've already read this other link: How to filter an array/object by checking multiple values, but I can not seem to adapt it to my case.

Thanks in advance!

EDIT: The condition on "power" property is not requested now

EDIT 2: Sorry, I've forgot to indicate that filter object can have multiple values for single property, like this:

var filter = {
   "family":[
       "Applique", "Faretto", "Lanterne"
   ],
   ...
   "volt":[
        "12", "230"
   ],
   ...
}

Upvotes: 4

Views: 230

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using Array.filter, Array.indexOf and Object.keys functions:

var result = models.filter(function(obj){
    var matched = true;
    Object.keys(obj).forEach(function(k){
        if (k === "power") {  // The condition on "power" property is not requested now
            return false;
        }
        if (filter[k] && filter[k].length && filter[k].indexOf(obj[k]) === -1) {
            matched = false;
        }
    });
    return matched;
});

console.log(JSON.stringify(result, 0, 4));

The console.log output:

[
    {
        "family": "Applique",
        "power": "8",
        "volt": "12",
        "color": "4100",
        "type": "E27",
        "ip": "20",
        "dimensions": "230x92"
    }
]

Upvotes: 5

AlonL
AlonL

Reputation: 6660

Try lodash's _.filter

For filtering greater/lower than they give this example here:

_.filter(users, _.conforms({ 'age': _.partial(_.gt, _, 38) }));

Upvotes: 0

Related Questions