Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Javascript Object only contains falsy values

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?

like image 614
Kris Avatar asked Jan 14 '16 11:01

Kris


People also ask

How do you know if an object has Falsy values?

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.

How do you know if something is Falsy?

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. }

How do you check if all object keys has values?

Use array.Object. values(obj) make an array with the values of each key. Save this answer.

Is an empty object truthy or Falsy?

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.


1 Answers

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;
    }
}
like image 125
Niet the Dark Absol Avatar answered Oct 29 '22 17:10

Niet the Dark Absol