how to check if all object keys has false values

Andrey Kryukov picture Andrey Kryukov · May 12, 2014 · Viewed 46.3k times · Source

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?

Answer

MattCochrane picture MattCochrane · Mar 25, 2018

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.