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

JavaScript:如何在对象数组的对象中搜索子字符串

筛选包含指定子串的对象数组

要从包含summary字段的对象数组中,筛选出该字段包含特定子串的对象,最简洁可靠的方式是结合数组的filter()方法与字符串的includes()方法:

  • 精准匹配(区分大小写):

    const targetSubstring = "Item 3.02";
    const filteredArray = yourObjectArray.filter(obj => obj.summary.includes(targetSubstring));
    
  • 不区分大小写匹配(按需使用):

    const targetSubstring = "Item 3.02";
    const filteredArray = yourObjectArray.filter(obj => 
      obj.summary.toLowerCase().includes(targetSubstring.toLowerCase())
    );
    

如果之前用match()未得到预期结果,通常是因为match()默认返回匹配结果数组而非布尔值,需要额外判断(比如obj.summary.match(targetSubstring) !== null),相比之下includes()更直接适配filter()的布尔判断需求。

完整示例:

// 示例对象数组
const items = [
  { id: 1, summary: "Item 3.01 - 测试内容" },
  { id: 2, summary: "Item 3.02 - 目标条目" },
  { id: 3, summary: "包含Item 3.02的补充记录" },
  { id: 4, summary: "Item 3.03 - 无关内容" }
];

// 执行筛选
const result = items.filter(item => item.summary.includes("Item 3.02"));
console.log(result);
// 输出:[{ id: 2, ... }, { id: 3, ... }]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:20:40