You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤对象中含指定数组元素的条目?现有函数未生效问题

问题原因

你的代码里用了words.includes(item)做判断,但errors里的错误信息是包含words里的短语(比如"'D54'. Unknown format."包含"Unknown format"),不是和短语完全相等。这个判断永远返回true,等于没过滤,所以会返回全部原始数据。

修复后的代码
function filterErrors(errors: any) {
    const obj: any = {};
    const words = [
      'Unknown format',
      'There is no number',
    ] as string[];

    for (const [key, value] of Object.entries(errors)) {
      const filtered = (value as string[]).filter(
        (item: string) => !words.some(word => item.includes(word))
      );

      // 只有过滤后还有剩余错误,才保留这个key
      if (filtered.length > 0) {
        obj[key] = filtered;
      }
    }

    return obj;
  }


let errors = {
    "1": ["'D54'. Unknown format."],
    "2": ["'K53'. There is no number."],
    "3": ["Valid entry", "Another valid message"]
}

console.log(filterErrors(errors));
关键修改点
  • 把!words.includes(item)改成!words.some(word => item.includes(word)):some会检查words里是否有任意一个短语被当前错误信息包含,只要有一个满足就返回true,取反后就能把包含这些短语的错误过滤掉。
  • 保留if (filtered.length > 0)逻辑:如果某个key下的所有错误都被过滤干净,就不会把这个key加入结果对象,符合你"排除包含指定数组元素的条目"的需求。

测试这段代码,结果只会保留"3"这个key,因为它的错误信息都不包含指定短语;"1"和"2"的错误会被完全过滤,不会出现在最终对象里。

内容的提问来源于stack exchange,提问作者Arvia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:55:18