简体   繁体   English

如何知道 javascript 数组 object 值是否为真?

[英]How to know if javascript array object values are true?

I have a simple array of objects.我有一个简单的对象数组。

  { id: 1, name: 'John', license: true },
  { id: 1, name: 'Sam', license: false },
  { id: 1, name: 'Luis', license: true }
];

How to make a reusable function to check: 1) if license property for all of them together is true 2) if one of license property is true如何制作可重复使用的 function 以检查:1)所有这些的许可属性是否为真 2)如果许可属性之一为真

You can check with these:你可以检查这些:

 const data = [{ id: 1, name: 'John', license: true }, { id: 1, name: 'Sam', license: false }, { id: 1, name: 'Luis', license: true } ]; var allTrue = data.every(i=> i.license === true); console.log(allTrue); var someTrue = data.some(k=> k.license === true) console.log(someTrue)

i hope this helps我希望这有帮助

 var array = [{ id: 1, name: 'John', license: true }, { id: 1, name: 'Sam', license: false}, { id: 1, name: 'Luis', license: true } ]; var trueCounter = 0; function checkValid(arr){ for(let obj of arr){ if(obj.license == true){ trueCounter++; } } if(trueCounter == array.length){ return "all items are true" } else if (trueCounter >= 1){ return "at least one item is true" } else { return "all items are false" } } console.log(checkValid(array));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM