这类似于this问题,除了针对不同数组评估多个属性。
我有以下foreach循环和执行所需功能的标志。
var countries = [...];
var religionFilter = ["religA", "religB"];
var believersFilter = ["many"];
var religionFilteredCountries = [];
_.forEach(countries,
c => {
let flag = false;
_.forEach(c.info, i => {
if (_.includes(religionFilter, i.religion) && _.includes(believersFilter, i.believers)) {
flag = true;
}
});
if (flag) {
religionFilteredCountries.push(c);
}
});
这是jsfiddle。
问题是如何将此代码转换为最小的lodash过滤器。
答案 0 :(得分:1)
您可以使用ES6完成此任务:
var religionFilteredCountries = countries.filter(c => c.info.find(i => religionFilter.includes(i.religion) && believersFilter.includes(i.believers)));
使用Lodash应该非常相似:
var religionFilteredCountries = _.filter(countries, c => _.find(c.info, i => _.includes(religionFilter, i.religion) && _.includes(believersFilter, i.believers)));