Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an object key only if value is true

How do i return an object key name only if the value of it is true?

I'm using underscore and the only thing i see is how to return keys which is easy, i want to avoid redundant iterations as much as possible:

example:

Object {1001: true, 1002: false}  

I want an array with only 1001 in it...

like image 305
user3299182 Avatar asked Aug 02 '14 13:08

user3299182


People also ask

How do you check if all object keys has false value?

To check if all of the values in an object are equal to false , use the Object. values() method to get an array of the object's values and call the every() method on the array, comparing each value to false and returning the result.


1 Answers

Object.keys gets the keys from the object, then you can filter the keys based on the values

var obj = {1001: true, 1002: false};  var keys = Object.keys(obj);  var filtered = keys.filter(function(key) {     return obj[key] }); 

FIDDLE

like image 194
adeneo Avatar answered Oct 06 '22 11:10

adeneo