我正在尝试寻找一种有效的方法来检查数组是否包含我期望的对象。在下面的示例中,我期望fruit
中的对象具有type
= apple, banana, and orange
这里是一个非常基本的解决方案:
const fruit = [
{'type': 'apple', 'color': 'red', 'quantity': 10},
{'type': 'banana', 'color': 'yellow', 'quantity': 9},
{'type': 'orange', 'color': 'orange', 'quantity': 3}
];
let fruitsToCheck = ['apple', 'banana', 'orange'];
let fruitsThatExist = [];
fruit.forEach( fruit => {
fruitsThatExist.push(fruit.type);
});
fruitsToCheck = fruitsToCheck.sort().toString();
fruitsThatExist = fruitsThatExist.sort().toString();
const allExist = fruitsToCheck === fruitsThatExist;
我有解决方案,但效率不高。什么是解决此问题的更好方法?
const allExist = fruitsToCheck.every(type =>
fruit.some(fruit => fruit.type === type)
)
const fruits = [
{'type': 'apple', 'color': 'red', 'quantity': 10},
{'type': 'banana', 'color': 'yellow', 'quantity': 9},
{'type': 'orange', 'color': 'orange', 'quantity': 3}
];
console.log(fruits.find(fruit => fruit.type === 'apple' || fruit.type === 'banana' || fruit.type === 'orange') !== undefined)