satJ satJ - 6 days ago 5
Javascript Question

How to use Lodash to make this mapping simpler?

I Have the following object:

var config = {
apps: false,
transfers: false,
approvals: true
};


I want to know how I can use Lodash to go through each of the keys within the
config
object and find out which key has the first occurrence of value
true
. In the example above, I expect the output to be
approvals
. If the value for
transfers
was
true
, I expect the output to be
transfers
.

Basically, I want a more cleaner way to do this:

if (config.apps) {
answer = 'apps';
} else if (config.transfers) {
answer = 'transfers';
} else if (config.approvals) {
answer = 'approvals';
}


Thanks!

Answer

You can use _.findKey():

var config = { apps: false, transfers: false, approvals: true };

var answer = _.findKey(config);

console.log(answer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

Or without lodash, you can use Array.prototype.reduce() with Object.keys():

var config = { apps: false, transfers: false, approvals: true };

var answer = Object.keys(config).reduce(function(answer, key) { 
  return value = config[key] ? key : answer;
}, '');

console.log(answer);

Comments