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
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With