Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if any key values are false in an object

Tags:

javascript

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 

like image 741
Kyle Avatar asked Nov 15 '16 14:11

Kyle


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 an object has any keys?

Using the Object.Object. keys() is a static method that returns an Array when we pass an object to it, which contains the property names (keys) belonging to that object. We can check whether the length of this array is 0 or higher - denoting whether any keys are present or not.


3 Answers

You can use the Array.some method:

var hasFalseKeys = Object.keys(ob).some(k => !ob[k]);
like image 142
tymeJV Avatar answered Oct 17 '22 10:10

tymeJV


Here's how I would do that:

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

// OR

Object.values(ob).indexOf(false) >= 0;  // Before ECMAScript 7
like image 45
Manoj Shrestha Avatar answered Oct 17 '22 12:10

Manoj Shrestha


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));
like image 1
Yosvel Quintero Arguelles Avatar answered Oct 17 '22 12:10

Yosvel Quintero Arguelles