I have a simple array that looks like
obj = {1:false, 2:true, 3:true}
I would like to retrieve an array of all keys in the object that have a value of true.
In python you can just do
>>> [key for key in obj if obj[key]]
[2, 3]
Is there a one-line or other simple way of doing this in Javascript? I also have access to lodash.
You can do this in any Ecma5 capable browser using Object.keys and Array.filter:
> Object.keys(obj).filter(function(i) {return obj[i]});
> ["2", "3"]
Using new javascript syntax, you can do it like this.
const obj = {1:false, 2:true, 3:true};
const res = Object.keys(obj).filter(k => obj[k]);
console.log(res);
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