如何使用lodash选择元素,其中内部属性与不同数组中的值匹配

时间:2018-03-11 21:57:26

标签: javascript typescript lodash

这类似于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过滤器。

1 个答案:

答案 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)));