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?
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]
});
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With