验证数组中一些对象的干净方法是什么?

问题描述 投票:0回答:4

我正在尝试寻找一种有效的方法来检查数组是否包含我期望的对象。在下面的示例中,我期望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;

我有解决方案,但效率不高。什么是解决此问题的更好方法?

javascript arrays node.js validation object
4个回答
0
投票

检出array.everyarray.some

const allExist = fruitsToCheck.every(type =>
  fruit.some(fruit => fruit.type === type)
)

0
投票

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)

0
投票

您可以在Set中收集类型,并以Set作为Set#has的回调进行检查。

Set#has
© www.soinside.com 2019 - 2024. All rights reserved.