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条回答
我只想做你的唯一
2楼-- · 2019-03-14 19:56

Short and handy one-liner, fully supported by browsers:

Object.keys(saver).every(k => saver[k] === false);

or

Object.values(saver).every(v => v === false);

(careful tho, Object.values() is not supported by IE yet.)

查看更多
smile是对你的礼貌
3楼-- · 2019-03-14 19:57

This will do the trick...

var result = true;

for (var i in saver) {
    if (saver[i] === true) {
        result = false;
        break;
    }
}

You can iterate objects using a loop, either by index or key (as above).

If you're after tidy code, and not repeating that then simply put it in a function...

Object.prototype.allFalse = function() { 
    for (var i in this) {
        if (this[i] === true) return false;
    }
    return true;
}

Then you can call it whenever you need, like this...

alert(saver.allFalse());

Here's a working sample...

Object.prototype.allFalse = function() { 
    for (var i in this) {
        if (this[i] === true) return false;
    }
    return true;
}

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

console.log("all are false - should alert 'true'");
console.log(saver.allFalse());

saver.body = true;

console.log("one is now true - should alert 'false'");
console.log(saver.allFalse());

查看更多
登录 后发表回答