dbj44
dbj44

Reputation: 1998

Filter array of objects using arrays of values?

Given the following array of objects:

var data = [
  {fruit: "apples", stock: false, season: true},
  {fruit: "peaches", stock: true, season: false},
  {fruit: "oranges", stock: false, season: false},
  {fruit: "pears", stock: false, season: true},
]

and these two arrays:

var fruits = ["apples", "peaches"]
var inv = ["stock"]

How can I filter the objects, from data, so that objects are kept:

So, in the above example, only peaches survive:

  var result = [
    {fruit: "peaches", stock: true, season: false}
  ]

Upvotes: 0

Views: 78

Answers (4)

sushant shrestha
sushant shrestha

Reputation: 21

var output = data.filter(val => {
    if (fruits.includes(val.fruit)) {
        return inv.filter(prop => {
            if (val[prop] == true)
                return val
        }).length > 0
    }
})
console.log(output)

I think this will do, if you just want to filter through.

Upvotes: 0

Just code
Just code

Reputation: 13801

You can use combination of filter and every here.

var data = [
  {fruit: "apples", stock: false, season: true},
  {fruit: "peaches", stock: true, season: false},
  {fruit: "oranges", stock: false, season: false},
  {fruit: "pears", stock: false, season: true},
]

var fruits = ["apples", "peaches"]
var inv = ["stock"]

var result= data.filter(a=> fruits.some(b=> b == a.fruit) && inv.every(k => a[k]));
console.log(result)

Upvotes: 0

Mark
Mark

Reputation: 92461

I think you can just use filter with some() and includes():

var data = [
  {fruit: "apples", stock: false, season: true},
  {fruit: "peaches", stock: true, season: false},
  {fruit: "oranges", stock: false, season: false},
  {fruit: "pears", stock: false, season: true},
]

var fruits = ["apples", "peaches"]
var inv = ["stock"]

let filtered = data.filter(item => 
    fruits.includes(item.fruit) && inv.some(i => item[i]))

console.log(filtered)

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386848

You could filter by looking in the fruits array with Array#includes and check the property by iterating inv with Array#every.

var data = [ { fruit: "apples", stock: false, season: true }, { fruit: "peaches", stock: true, season: false }, { fruit: "oranges", stock: false, season: false }, { fruit: "pears", stock: false, season: true }],
    fruits = ["apples", "peaches"],
    inv = ["stock"],
    result = data.filter(o => fruits.includes(o.fruit) && inv.every(k => o[k]));
   
console.log(result);

Upvotes: 2

Related Questions