Reputation: 1998
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:
fruit
in the fruits
array; ANDinv
array which is set to trueSo, in the above example, only peaches survive:
var result = [
{fruit: "peaches", stock: true, season: false}
]
Upvotes: 0
Views: 78
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
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
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
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