【发布时间】:2022-01-10 05:24:38
【问题描述】:
我正在尝试过滤一大组数据,其中包含一个嵌套在我需要与字符串比较的值中的数组。为了比较它们,我需要清理字符串,因为它来自用户输入和间距/大写可能会有所不同。所以我让我的函数通过一个看起来像这样的过滤器工作
数据最初看起来像
formularyOptions = [{Condition: "headache"...}{Condition: "hair loss"..}...]
chiefComplaint = "Headache"
const cleanText = (value) => {
let str = value;
if (!str) {
return value;
}
str = str.toLowerCase();
str = str.replace(/\s/g, "");
return str;
};
let formularyList = formularyOptions.filter(
(item) => !!chiefComplaint && cleanText(item.Condition) === cleanText(chiefComplaint),
);
这工作得很好,但现在
我的数据如下所示:
[{Condition: ["headache", "migraine"]...}{Condition: ["hair loss"]..}...]
我尝试更改过滤器以循环遍历条件数组,但由于某种我不明白的原因,它没有返回任何内容。并且包含方法不起作用,因为它区分大小写。关于如何解决这个问题,甚至为什么 forEach 不能在 .filter 中工作的任何建议都会非常有帮助,这是我对 for 循环的尝试:
let formularyList = formularyOptions.filter(
(item) => !!chiefComplaint && item.Condition.forEach((condition) => cleanText(condition) === cleanText(chiefComplaint)),
);
它只返回一个空数组..
【问题讨论】:
-
forEach不返回任何值 - 您似乎期望它返回一个布尔值。改用every -
感谢您的回复,我不认为 .every 可以工作,因为它测试数组中的所有元素是否通过测试,并且某些数组内部会有多个值,我只需要一个通过它被接受。这有意义吗?
标签: javascript arrays sorting filter foreach