如何根据其他数组的值过滤对象数组?

时间:2020-01-01 21:47:36

标签: javascript

const Fruits = [
{name:"Apple", color:"red", type:"fruit", condition:"new"},
{name:"Apple", color:"green", type:"fruit", condition:"new"},
{name:"Banana", color:"yellow", type:"fruit", condition:"new"},
{name:"Banana", color:"green", type:"fruit", condition:"new"},
{name:"Grape", color:"green", type:"fruit", condition:"older"},
{name:"Onion", color:"yellow", type:"greenery", condition:"new"},
]

const filter = ["fruit", "green", "new"];

如何仅使用值来过滤忽略键的数组?我尝试使用过滤器,但只返回一个类别

let result = Fruits.filter(e => filter.includes(e.type))

我想要这样的结果:

  result = [
     {name:"Apple", color:"green", type:"fruit", condition:"new"},
     {name:"Banana", color:"green", type:"fruit", condition:"new"},
    ]

2 个答案:

答案 0 :(得分:0)

在迭代过程中,使用Object.values()获取每个对象的值的数组,然后使用.every测试过滤器Array中的所有值是否匹配

const Fruits = [
  {name:"Apple", color:"red", type:"fruit", condition:"new"},
  {name:"Apple", color:"green", type:"fruit", condition:"new"},
  {name:"Banana", color:"yellow", type:"fruit", condition:"new"},
  {name:"Banana", color:"green", type:"fruit", condition:"new"},
  {name:"Grape", color:"green", type:"fruit", condition:"older"},
  {name:"Onion", color:"yellow", type:"greenery", condition:"new"},
]

const filter = ["fruit", "green", "new"];

const newArray = Fruits.filter((fruit) => {
  return filter.every(x => Object.values(fruit).includes(x));
});

console.log(newArray);

答案 1 :(得分:0)

我的理解是,您想通过Fruitscolortype键过滤condition数组,如果其中任何一个包含{ {1}}数组,则应将它们包含在过滤结果中。

一个简单的解决方案是使用Array#includes通过以下过滤器逻辑:

filter

基于您的代码段的完整示例如下:

// fruit is current array item in Fruits being tested/filtered
filter.includes(fruit.color) && 
filter.includes(fruit.type) && 
filter.includes(fruit.condition)

希望有帮助!