使用Lodash根据另一个对象的真实状态获取对象的值

时间:2018-10-22 14:46:52

标签: javascript lodash

我想用Lodash来获得每只具有真实价值的动物的标签。

预期结果:['DOG', 'CAT']

是否有一种无需使用result.push的方法?

如何使trueKeysLabellabelList获取动物标签?

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>

我尝试过_.get,但是在_.forEach中使用它时,trueKeysLabel等于键['dog', 'cat']而不是它们的值。

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

4 个答案:

答案 0 :(得分:1)

使用_.filter()labelList中获取其键的值为true中的值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>

答案 1 :(得分:0)

我敢肯定有几种方法可以做到这一点,但是下面的内容可以满足您使用_.pickBy_.identity_.keys_.filter的要求,和_.includes

var result = [],
  labelList = {
    dog: 'DOG',
    cat: 'CAT',
    monkey: 'MONKEY'
  },
  animalList = {
    dog: true,
    cat: true,
    monkey: false
  };

// pickBy will return an object of "truthy" values.
// keys then creates an array of the resultant object keys - ["dog", "cat"]
var keys = _.keys(_.pickBy(animalList, _.identity));

// filter will return only those values the predicate function returns truthy for
results = _.filter(labelList, function(val, key) {
  // return true if the key is in the list of "truthy" keys
  return (_.includes(keys, key));
});

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

答案 2 :(得分:0)

使用_.values()

_.forEach(trueKeys, function(key) {
      result.push(_.values(labelList[key]));
});

答案 3 :(得分:0)

您也不需要其他库来执行此操作。您可以先执行Object.entries然后执行filter,最后执行map以获取值:

var labelList = { dog: 'DOG', cat: 'CAT', monkey: 'MONKEY' }, animalList = { dog: true, cat: true, monkey: false }

const r = Object.entries(labelList).filter(x => animalList[x[0]]).map(x => x[1])

console.log(r)