how to check if all object keys has false values

2019-03-14 19:15发布

JS Object:

var saver = {
        title: false,
        preview: false,
        body: false,
        bottom: false,
        locale: false
};

The question is how to check if all values is false?

I can use $.each() jQuery function and some flag variable, but there may be a better solution?

8条回答
倾城 Initia
2楼-- · 2019-03-14 19:34

If you want to do it without external iteration (i.e. in your code), try mapping the properties to an array with $.map then using $.inArray to see if any true values exist:

var allFalse = $.inArray(true, $.map(saver, function(obj){return obj})) < 0;

JSFiddle: http://jsfiddle.net/TrueBlueAussie/FLhZL/1/

查看更多
beautiful°
3楼-- · 2019-03-14 19:37

In a comment you ask if you can avoid iteration. You can if you use a javascript library supporting a functional approach, like Underscore, Lodash or Sugar.

With Underscore and Lodash you can write something like this:

var result = _.every(_.values(saver), function(v) {return !v;});

With Sugar you can simply write:

var result = Object.all(saver,false);
查看更多
祖国的老花朵
4楼-- · 2019-03-14 19:37

With lodash you could also do const result = _.some(saver);

查看更多
Juvenile、少年°
5楼-- · 2019-03-14 19:38

Do like this,

 for (var i in saver) {
  if (saver[i]) {
    return false; // here if any value is true it wll return as false /
  }
 }
 return true; //here if all value is false it wll return as true
查看更多
Rolldiameter
6楼-- · 2019-03-14 19:43

As of Lodash 4.0, overEvery can be used

overEvery(saver, false) loops through every element & checks if its false

It returns true if every element is false otherwise returns false

查看更多
爷、活的狠高调
7楼-- · 2019-03-14 19:51

This is a very simple solution that requires JavaScript 1.8.5.

Object.keys(obj).every((k) => !obj[k])

Examples:

obj = {'a': true, 'b': true}
Object.keys(obj).every((k) => !obj[k]) // returns false

obj = {'a': false, 'b': true}
Object.keys(obj).every((k) => !obj[k]) // returns false

obj = {'a': false, 'b': false}
Object.keys(obj).every((k) => !obj[k]) // returns true

Alternatively you could write

Object.keys(obj).every((k) => obj[k] == false)
Object.keys(obj).every((k) => obj[k] === false)  // or this
Object.keys(obj).every((k) => obj[k])  // or this to return true if all values are true

See the Mozilla Developer Network Object.keys()'s reference for further information.

查看更多
登录 后发表回答