我想用Lodash来获得每只具有真实价值的动物的标签。
预期结果:['DOG', 'CAT']
是否有一种无需使用result.push
的方法?
如何使trueKeysLabel
从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>
我尝试过_.get
,但是在_.forEach
中使用它时,trueKeysLabel
等于键['dog', 'cat']
而不是它们的值。
var trueKeysLabel = _.forEach(trueKeys, function(key) {
return _.get(labelList, key);
});
答案 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)