Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object keys for filtered values

The case is simple - I've got a following object:

Object {1: false, 2: true, 3: false, 4: false, 5: false, 6: false, 7: false, 8: true, 12: false, 13: false, 14: false, 15: false, 16: false, 17: false, 18: false, 19: false}  

and I need to get an array of ids that had true value, using underscore. In above case that would be:

[2, 8] 

I tried few things but I'm a bit stuck. Does anyone have any idea?

like image 946
ducin Avatar asked Jun 07 '13 15:06

ducin


1 Answers

var keys = []; _.each( obj, function( val, key ) {   if ( val ) {     keys.push(key);   } }); 

There may be easier/shorter ways using plain Underscore.


In case anyone here uses Lodash instead of Underscore, the following is also possible, which is very short and easy to read:

var keys = _.invert(obj, true)[ "true" ]; 
like image 152
gustavohenke Avatar answered Sep 22 '22 04:09

gustavohenke