如何显示包含数组中所有项目的所有对象 - javascript

How to display all objects that contain all item from array - javascript

这里需要一些帮助。寻找解决此问题的提示:

目标是过滤 arrayOfObject 并获取包含给定的所有元素的 属性 fruits 的所有对象数组。

  const arrayOfObject = [
  {
    id: 1,
    country: 'USA',
    fruits: ["APPLE", "ORANGE", "BANANA"]
  },
  {
    id: 2,
    country: 'Canada',
    fruits: ["APPLE"]
  },
  {
    id: 3,
    country: 'France',
    fruits: ["ORANGE", "BANANA", "LEMON"]
  },
  {
    id: 4,
    country: 'Mexico',
    fruits: ["BANANA", "PYTHON", "CHERRY"]
  },
  {
    id: 5,
    country: 'Ukraine',
    fruits: ["APPLE", "ORANGE", "CHERRY"]
  },
  {
    id: 6,
    country: 'Italy',
    fruits: ["APPLE", "ORANGE", "BANANA", "LEMON", "CHERRY"]
  }
];

给定数组的第一个例子:

const firstArrayOfFruits = ["APPLE","ORANGE","BANANA"];

应该渲染 =>

[
  {
    id: 1,
    country: 'USA',
    fruits: ["APPLE", "ORANGE", "BANANA"]
  },
  {
    id: 6,
    country: 'Italy',
    fruits: ["APPLE", "ORANGE", "BANANA", "LEMON", "CHERRY"]
  }
]

给定数组的第二个例子:

const secondArrayOfFruits = ["APPLE","ORANGE"];

应该渲染 =>

[
  {
    id: 1,
    country: 'USA',
    fruits: ["APPLE", "ORANGE", "BANANA"]
  },
  {
    id: 5,
    country: 'Ukraine',
    fruits: ["APPLE", "ORANGE", "CHERRY"]
  },
  {
    id: 6,
    country: 'Italy',
    fruits: ["APPLE", "ORANGE", "BANANA", "LEMON", "CHERRY"]
  }
]

您可以使用 Array.prototype.filter:

const arrayOfObject = [{
    id: 1,
    country: 'USA',
    fruits: ["APPLE", "ORANGE", "BANANA"]
  },
  {
    id: 2,
    country: 'Canada',
    fruits: ["APPLE"]
  },
  {
    id: 3,
    country: 'France',
    fruits: ["ORANGE", "BANANA", "LEMON"]
  },
  {
    id: 4,
    country: 'Mexico',
    fruits: ["BANANA", "PYTHON", "CHERRY"]
  },
  {
    id: 5,
    country: 'Ukraine',
    fruits: ["APPLE", "ORANGE", "CHERRY"]
  },
  {
    id: 6,
    country: 'Italy',
    fruits: ["APPLE", "ORANGE", "BANANA", "LEMON", "CHERRY"]
  }
];

const firstArrayOfFruits = ["APPLE", "ORANGE", "BANANA"];

var arr = arrayOfObject.filter(item => item.fruits.filter(fruit => firstArrayOfFruits.indexOf(fruit) + 1).length >= firstArrayOfFruits.length);
console.log(arr);

使用 ES6 some() 函数很有用,因为当找到一个条目时它会 return true 并且不检查其余部分,因此您可以节省一些计算、时间和 CPU

const filtered = arrayOfObject.filter(obj => {
       if(obj.fruits.some(fruit => fruitsLisToCheck.includes(fruit)))
         return obj
    })

const fruitsLisToCheck = ['BANANA', 'APPLE'];

const arrayOfObject = [
  {
    id: 2,
    country: 'Canada',
    fruits: ["APPLE"]
  },
  {
    id: 3,
    country: 'France',
    fruits: ["BANANA"]
  },
  {
    id: 4,
    country: 'Mexico',
    fruits: ["CHERRY"]
  },
];