religionFilteredCountries

religionFilteredCountries

本文介绍了选择内部属性与数组中的值匹配的lodash元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下内容,并且想知道是否有一种更简洁的方法来执行此操作,因为我不喜欢包含该标志.

I currently have the following and want to know if there is a cleaner way to do it since I do not like the inclusion of the flag.

const countries = [...];
const religionFilter = [ "religA", "religB" ];
const religionFilteredCountries = [];

_.forEach(countries,
    c => {
        let flag = false;

        _.forEach(c.info, i => {
            if (_.includes(religionFilter, i.religions)) {
                flag = true;
            }
        });
        if (flag) {
            religionFilteredCountries.push(c);
        }
    }
);

这是 jsfiddle .

这是更新的 jsfiddle .

推荐答案

由于您已经在使用lodash,因此可以这样编写religionFilteredCountries:

Since you're already using lodash, you can write religionFilteredCountries like this:

const religionFilteredCountries =
  countries.filter((c) => _.intersection(religionFilter, c.religions).length > 0);

这篇关于选择内部属性与数组中的值匹配的lodash元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 14:05