Selecting elements with lodash where inner properties match values in an array

╄→гoц情女王★ 提交于 2019-12-24 18:31:54

问题


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);
        }
    }
);

Here is a jsfiddle.


Here is the updated jsfiddle.


回答1:


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

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


来源:https://stackoverflow.com/questions/49076600/selecting-elements-with-lodash-where-inner-properties-match-values-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!