Search code examples
javascriptlodash

Use Lodash to get object's values based on another object's truthy state


I want to use Lodash to get the label for each animal with true value.

Expected result: ['DOG', 'CAT']

Is there a way to do this without using result.push?.

How can I make trueKeysLabel gets the animal label from labelList?

var result = [],
  labelList = {
    dog: 'DOG',
    cat: 'CAT',
    monkey: 'MONKEY'
  },
  animalList = {
    dog: true,
    cat: true,
    monkey: false
  }
trueKeys = _.filter(_.keys(animalList), function(key) {
  return animalList[key];
});

_.forEach(trueKeys, function(key) {
  result.push(_.get(labelList, key));
});

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

I have tried _.get but when it is used within _.forEach, trueKeysLabel equals the keys ['dog', 'cat'] instead of their values.

var trueKeysLabel = _.forEach(trueKeys, function(key) {
    return _.get(labelList, key);
});

Solution

  • Use _.filter() to get the values from labelList that their key's value is true in animalList:

    var labelList = {
        dog: 'DOG',
        cat: 'CAT',
        monkey: 'MONKEY'
      },
      animalList = {
        dog: true,
        cat: true,
        monkey: false
      };
    
    var result = _.filter(labelList, (v, k) => animalList[k]); 
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>