你可以很容易地做到这一点
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']
为此,您只需稍微扩展下划线:
_.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;
}
});
您甚至可以使用函数作为过滤器,如下所示:
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']
享受 ;-)