问题
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