在过滤器中使用 forEach 来组织数据

Using a forEach inside a filter to organize data

我正在尝试筛选大量数据,这些数据的数组嵌套在我需要与字符串进行比较的 whos 值中。为了比较它们,我需要清理字符串,因为它来自用户输入并且 spacing/capitalization 可能会有所不同。所以我让我的函数通过一个看起来像这样的过滤器工作

数据最初看起来像

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"]..}...]

我试过更改我的过滤器以循环遍历条件数组,但由于某种我不明白的原因,这 return 没有任何作用。并且 includes 方法不会工作,因为它区分大小写。关于如何解决这个问题甚至为什么 forEach 不能在 .filter 中工作的任何建议都会非常有帮助这是我对 for 循环的尝试:

let formularyList = formularyOptions.filter(
      (item) => !!chiefComplaint && item.Condition.forEach((condition) => cleanText(condition) === cleanText(chiefComplaint)),
      
    );

这只是 return 一个空数组..

您在布尔条件中包含了一个 .forEach(...),但它是无效的,它只会循环,不会返回任何内容。

我认为你实际上需要使用 .some(...) 来代替,它会尝试找到一些符合条件的项目:

let formularyList = formularyOptions.filter(
      (item) => !!chiefComplaint && item.Condition.some((condition) => cleanText(condition) === cleanText(chiefComplaint)),
      
    );