Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if all javascript object values are true?

Tags:

javascript

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.

like image 359
napalias Avatar asked Jun 14 '13 21:06

napalias


People also ask

How do you check if all object keys has false value?

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.

How do you check if all values in array are true JavaScript?

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!

Are objects true in JavaScript?

All objects (including arrays and functions) convert to true.


1 Answers

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) 
like image 196
Nachiketha Avatar answered Sep 29 '22 07:09

Nachiketha