Check if any key values are false in an object

Question:

I’m looking for a simple solution to check if any key values are false in an object.

I have an object with several unique keys, however, they only contain boolean values (true or false)

var ob = {  stack: true, 
            overflow: true, 
            website: true 
         };

I know that I can get the number of keys in an Object, with the following line:

Object.keys(ob).length // returns 3

Is there a built in method to check if any key value is false without having to loop through each key in the object?


Solution:

To check if any keys – use Array.prototype.some().

// to check any keys are false
Object.keys(ob).some(k => !ob[k]); // returns false

To check if all keys – use Array.prototype.every().

// to check if all keys are false 
Object.keys(ob).every(k => !ob[k]); // returns false 

You can use the Array.some method:

var hasFalseKeys = Object.keys(ob).some(k => !ob[k]);

Here’s how I would do that:

Object.values(ob).includes(false);      // ECMAScript 7

// OR

Object.values(ob).indexOf(false) >= 0;  // Before ECMAScript 7

You can create an arrow function isAnyKeyValueFalse, to reuse it in your application, using Object.keys() and Array.prototype.find().

Code:

const ob = {
  stack: true,
  overflow: true,
  website: true
};
const isAnyKeyValueFalse = o => !!Object.keys(o).find(k => !o[k]);

console.log(isAnyKeyValueFalse(ob));

To check if all values are false

Object.values(ob).every(v => !v); 

enter image description here


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   How to get the response of XMLHttpRequest?

Similar Posts