I got an object like this :
var obj1 = {foo: false, bar: ''};
var obj2 = {foo: false, bar: '1'};
var obj3 = {foo: true, bar: ''};
var obj4 = {foo: true, bar: '1'};
I want a simple function to check those objects if all of their values are false or not. In this given example only obj1 should trigger a false - cause all of their values are false. obj2
, obj3
and obj4
own at least one value which is true.
Is there a simple solution to do this?
To check if an object only contains falsy values:Use Object. values() to get an array of the object's values. Call the every() method on the array. Convert each value to boolean, invert it, and return the result.
Checking for falsy values on variables It is possible to check for a falsy value in a variable with a simple conditional: if (! variable) { // When the variable has a falsy value the condition is true. }
Use array.Object. values(obj) make an array with the values of each key. Save this answer.
There are only seven values that are falsy in JavaScript, and empty objects are not one of them. An empty object is an object that has no properties of its own. You can use the Object.
As a one-liner:
!Object.keys(obj1).some(function(k) {return obj1[k];});
// Array.some returns true if any callback returns true
// You want true if all return false, aka if none return true
// So just negate Array.some
As a more readable method:
var ok = true, k;
for( k in obj1) if( obj1.hasOwnProperty(k)) {
if( obj1[k]) {
ok = false;
break;
}
}
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