Get object keys for filtered values

2020-05-24 20:33发布

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?

14条回答
孤傲高冷的网名
2楼-- · 2020-05-24 21:16

Heres a way to do it without using any libraries in ES6

let z = {2: true, 3:false, 8:true, 9:false, 10: false}
Array.from(new Set(Object.keys(z).map(function(k){if(z[k]){return k}}))).filter(f=>f)

and out you get [2, 8]

查看更多
倾城 Initia
3楼-- · 2020-05-24 21:17

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;
}));
查看更多
登录 后发表回答