给出以下对象数组:
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"]
如何从data
过滤对象,以便保留对象:
fruit
数组中有fruits
;和inv
数组中的属性,该属性设置为true 因此,在上面的示例中,只有桃子可以存活:
var result = [
{fruit: "peaches", stock: true, season: false}
]
答案 0 :(得分:3)
我认为您可以只将过滤器与some()
和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 }],
fruits = ["apples", "peaches"],
inv = ["stock"],
result = data.filter(o => fruits.includes(o.fruit) && inv.every(k => o[k]));
console.log(result);
答案 1 :(得分:2)
答案 2 :(得分:0)
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)
答案 3 :(得分:0)
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)
如果您只想过滤通过,我认为这可以。