Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find properties of JS object with truthy values using lodash

Let's say I have an object like:

var foo = {
    alpha: true,
    beta: false,
    gamma: true
}

I can use _.findKey to get one key with a true value, but I'd really like to get an array containing all keys with a true value. E.g.

_.findAllKeys(foo, function(val) { return val; });
// yields -> ["alpha", "gamma"]

It's simple enough to write a function to do this, but it seems like such an obvious generalization of findKey that I feel I must just be missing it. Does lodash have such a function?

like image 215
Asmor Avatar asked Apr 03 '15 23:04

Asmor


2 Answers

We can use pickBy() in lodash to get the key for which value equal to true.

const active = _.keys(_.pickBy(foo));

Alternatively we can also use,

var active = _.keys(foo).filter(function (id) {
    return foo[id]
});
like image 135
Subrata Sarkar Avatar answered Nov 02 '22 17:11

Subrata Sarkar


I found an answer which simultaneously feels kludgy and elegant.

var foo = {
    alpha: true,
    beta: false,
    gamma: true
};
_.invert(foo, true).true

// yields -> ["alpha", "gamma"]
like image 32
Asmor Avatar answered Nov 02 '22 18:11

Asmor