Find properties of JS object with truthy values using lodash
var foo = {
alpha: true,
beta: false,
gamma: true
};
var t1 = _.keys(_.pick(foo, _.identity));
console.log(t1);
var t2 = _(foo).pick(_.identity).keys().value();
console.log(t2);
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
Edit:
As noted by @backdesk, _.pick
no longer works for lodash 4 because _.pickBy
was split out.
var foo = {
alpha: true,
beta: false,
gamma: true
};
var t1 = _.keys(_.pickBy(foo, _.identity));
console.log(t1);
var t2 = _(foo).pickBy(_.identity).keys().value();
console.log(t2);
// _.pickBy defaults to _.identity
var t3 = _.keys(_.pickBy(foo));
console.log(t3);
var t4 = _(foo).pickBy().keys().value();
console.log(t4);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.8.2/lodash.min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
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"]
pickBy in loDash by default uses _.identity
to filter properties
so you can use it like this:
_.pickBy({'a': undefined, 'b':1, c:{}});
// => Object {b: 1, c: Object}