首页 > 解决方案 > 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

标签: javascriptarraysobject

解决方案


我希望这有帮助

 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));


推荐阅读