Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  131] [ 1]  / answers: 1 / hits: 85166  / 11 Years ago, fri, june 14, 2013, 12:00:00

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.


More From » javascript

 Answers
78

How about something like:





    function allTrue(obj)
{
for(var o in obj)
if(!obj[o]) return false;

return true;
}

var myObj1 = {title:true, name:true, email:false};
var myObj2 = {title:true, name:true, email:true};

document.write('<br />myObj1 all true: ' + allTrue(myObj1));
document.write('<br />myObj2 all true: ' + allTrue(myObj2));






A few disclaimers: This will return true if all values are true-ish, not necessarily exactly equal to the Boolean value of True. Also, it will scan all properties of the passed in object, including its prototype. This may or may not be what you need, however it should work fine on a simple object literal like the one you provided.


[#77616] Thursday, June 13, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
cadendericki questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Wed, Jul 8, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
;