Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if all object keys has false values

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?

like image 460
Andrey Kryukov Avatar asked May 12 '14 08:05

Andrey Kryukov


People also ask

How do you check if an object contains a value?

You can use Object. values(): and then use the indexOf() method: Show activity on this post.


1 Answers

Updated version. Thanks @BOB for pointing out that you can use values directly:

Object.values(obj).every((v) => v === false) 

Also, the question asked for comparison to false and most answers below return true if the object values are falsy (eg. 0, undefined, null, false), not only if they are strictly false.


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.

like image 140
MattCochrane Avatar answered Sep 24 '22 23:09

MattCochrane