In JavaScript, I need to know if all object items are set to true.
If I have the following object:
var myObj = {title:true, name:true, email:false};
I could write something like this :
if(myObj.title && myObj.name && myObj.email){ /*Some code */ };
But I am looking for the simplest way to write it. eg :
if(myObj all is true){ /*Some code */ };
I might have another object with 10-20 items inside it, and will need to know if all are true.
To check if all of the values in an object are equal to false , use the Object. values() method to get an array of the object's values and call the every() method on the array, comparing each value to false and returning the result.
To check if all of the values in an array are equal to true , use the every() method to iterate over the array and compare each value to true , e.g. arr. every(value => value === true) . The every method will return true if the condition is met for all array elements. Copied!
All objects (including arrays and functions) convert to true.
With ES2017 Object.values() life's even simpler.
Object.values(yourTestObject).every(item => item)
Even shorter version with Boolean() function [thanks to xab]
Object.values(yourTestObject).every(Boolean)
Or with stricter true checks
Object.values(yourTestObject) .every(item => item === true)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With