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条回答
可以哭但决不认输i
2楼-- · 2020-05-24 21:02
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();
查看更多
不美不萌又怎样
3楼-- · 2020-05-24 21:03

Another potential solution:

// Your example data
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};

// Outputs the keys: ["2", "8"]
_.keys(_.transform(data, function(r, v, k) { v ? r[k] = 1 : null; }));

// Outputs the keys as integers: [2, 8]
_.map(_.keys(_.transform(data, function(r, v, k) { v ? r[k] = 1 : null; })), _.parseInt)

So basically:

  1. Transform the original object to strip out the false-valued keys
  2. Grab the list of keys from the transformed result
  3. Convert the keys to ints if you need to
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-05-24 21:05

My version:

var list = {
    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
};

_.chain(list).map(function(val, key) {
    return val ? parseInt(key) : undefined
}).reject(function(val) {
    return _.isUndefined(val);
}).value();
// returns [2,8]
查看更多
三岁会撩人
5楼-- · 2020-05-24 21:09

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)
查看更多
We Are One
6楼-- · 2020-05-24 21:12
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]
查看更多
Viruses.
7楼-- · 2020-05-24 21:14

I use this one: Retrieve all keys with the same value from an object (not only an object with just boolean values) using lodash

function allKeys(obj, value) {
  _.keys(_.pick(obj, function (v, k) { return v === value; }));
}

Example:

var o = {a: 3, b: 5, c: 3};
var desiredKeys = allKeys(o, 3);
// => [a, c]
查看更多
登录 后发表回答