简体   繁体   中英

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 

您可以使用Array.some方法:

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); 

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM