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
var data = {1: false, 2: true, 3: false, 4: true};
var filteredIds = _.filter(_.keys(data), function (key) {
return data[key];
});
// result [2, 4]
var rejectedIds = _.reject(_.keys(data), function (key) {
return data[key];
});
// result [1, 3]
var obj = {1: false, 2: true /*...*/};
you can use reduce:
_(obj).reduce(function(memo, val, key){
if (val)
memo.push(key);
return memo;
}, []);
or chain map:
_(obj).chain().map(function(val, key){
if (val)
return key;
}).reject(_.isUndefined).value();
You can use _.pick
. Like this:
var data = {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}
var keys = _.keys(_.pick(data, function(value) {
return value;
}));
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" ];
You can do it very easily
var obj = { a: false, b: false, c: true, d: false, e: true, f: false };
name, names;
name = _.findKey(obj, true);
// -> 'c'
names = _.findKeys(obj, true);
// -> ['c', 'e']
For that you juste need to extend underscore a little :
_.mixin({
findKey: function(obj, search, context) {
var result,
isFunction = _.isFunction(search);
_.any(obj, function (value, key) {
var match = isFunction ? search.call(context, value, key, obj) : (value === search);
if (match) {
result = key;
return true;
}
});
return result;
},
findKeys: function(obj, search, context) {
var result = [],
isFunction = _.isFunction(search);
_.each(obj, function (value, key) {
var match = isFunction ? search.call(context, value, key, obj) : (value === search);
if (match) {
result.push(key);
}
});
return result;
}
});
And you can even use a function as filter, like this :
var team = {
place1: { name: 'john', age: 15 },
place2: { name: 'tim', age: 21 },
place3: { name: 'jamie', age: 31 },
place4: { name: 'dave', age: 17 }}
// Determine the places of players who are major
var placeNames = _.findKeys(team, function(value) { return value.age >= 18; });
// -> ['place2', 'place3']
Enjoy ;-)
Giorgi Kandelaki gave a good answer, but it had some potential problems (see my comment on his answer).
The correct way is:
_(obj).pairs().filter(_.last).map(_.first)
or
_.map(_.filter(_.pairs(obj),_.last),_.first)