I have the object pks
and would like to extract all keys where the value is true
.
pks = {3: false, 7: true, 2: true}
Is there an underscore function that can return [7, 2]
? I’ve tried _.invert
but I lost one of the values in the process so I’m looking for an alternative.
To get an object's key by it's value:Call the Object. keys() method to get an array of the object's keys. Use the find() method to find the key that corresponds to the value. The find method will return the first key that satisfies the condition.
Use array.Object. values(obj) make an array with the values of each key. Save this answer.
For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.
You can do this with builtin functions, no need for Underscore:
Object.keys(pks)
.filter(function(k){return pks[k]})
.map(Number)
Try this:
_.reduce(pks, function(memo, val, key){
if (val) memo.push(key);
return memo;
}, []);
Lodash:
_.compact(_.map(pks, function(value, prop) {
if(value) {
return prop;
}
}));
I would use Object.entries(), filter() and map():
const pks = {3: false, 7: true, 2: true};
const trueKeys = Object.entries(pks).filter(([_, v]) => v).map(([k, _]) => +k);
console.log(trueKeys);
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