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

如何筛选包含特定单词的数组?求完整解决方案

筛选数组中包含指定关键词的所有项

目标数组

{
 [
  {
    "id": 1,
    "name": "this is book",
  },
  {
    "id": 2,
    "name": "this is a test book",
  },
  {
    "id": 3,
    "name": "this is a desk",
  }
 ]
}

需求

返回所有name字段包含单词book的数组项。

原有代码问题分析

  • 第一段代码错误:s.name===book中book未加引号,会被识别为变量而非字符串;且===是严格全等匹配,只能匹配完全一致的字符串,无法检测包含关系。
  • 第二段代码错误:s.name===this is book存在语法错误,字符串未加引号;即便修正引号,===依然只能匹配name完全等于this is book的项,无法返回所有包含book的结果。

正确解决方案

使用String.includes()方法检测字符串是否包含指定子串,结合filter()遍历数组返回所有符合条件的项:

// 假设this.pro为目标数组
let test = this.pro.filter((s: { name: string; }) => s.name.includes('book'));

扩展:忽略大小写匹配

如果需要不区分大小写筛选,可将字符串统一转为小写(或大写)后再检测:

let test = this.pro.filter((s: { name: string; }) => s.name.toLowerCase().includes('book'));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:25:29