获取过滤值的对象键 [英] 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}
并且我需要使用下划线获取具有真值的 id 数组.在上述情况下,将是:
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?
推荐答案
var keys = [];
_.each( obj, function( val, key ) {
if ( val ) {
keys.push(key);
}
});
使用普通下划线可能有更简单/更短的方法.
如果这里有人使用 Lodash 而不是 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" ];
这篇关于获取过滤值的对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文