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

如何在嵌套数组对象结构中搜索含指定字符的元素?

数组筛选逻辑实现

原始数组结构

const originalArray = [
  { key: "001", value: [{ Id: "2345", Name: "Test" }] },
  { key: "112", value: [{ Id: "1234", Name: "UHV" }, { Id: "3424", Name: "ABC" }] },
  { key: "222", value: [{ Id: "2312", Name: "ABD" }, { Id: "1321", Name: "RFV" }, { Id: "4567", Name: "ERF" }] }
];

需求说明

当搜索字符AB时,筛选出满足以下条件的元素:

  • 父元素的value数组中存在子项的Name包含AB
  • 仅保留父元素中符合条件的子项,剔除不符合的子项

实现代码

const searchKeyword = 'AB';
const filteredResult = originalArray
  .map(item => {
    // 筛选当前项value中Name包含搜索关键词的子元素
    const matchedSubItems = item.value.filter(subItem => subItem.Name.includes(searchKeyword));
    // 有匹配结果则返回更新后的对象,否则返回null
    return matchedSubItems.length ? { ...item, value: matchedSubItems } : null;
  })
  // 过滤掉无匹配结果的父元素
  .filter(item => item !== null);

console.log(filteredResult);

输出结果

[
  { key: "112", value: [{ Id: "3424", Name: "ABC" }] },
  { key: "222", value: [{ Id: "2312", Name: "ABD" }] }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:57:12