使用值数组过滤对象数组?

时间:2018-09-19 17:03:07

标签: javascript

给出以下对象数组:

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}
  ]

4 个答案:

答案 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)

您可以使用Array#includes在Fruits数组中进行筛选,并通过Array#every迭代map来检查属性。

inv

答案 2 :(得分:0)

您可以在此处使用filterevery的组合。

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)

如果您只想过滤通过,我认为这可以。