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

嵌套数组过滤需求:匹配子项关键词并保留原结构

解决嵌套数组过滤并保留原结构的问题

嘿,我看你之前的代码在处理嵌套数组过滤时,不小心给父元素新增了额外的nome字段,这显然不符合你的需求。咱们来调整逻辑,完美实现你要的效果:支持模糊搜索关键词、保留原数组结构,没匹配到子元素的父元素data留空数组。

核心思路

我们需要只修改每个父元素里的data数组,其他原有属性(比如title)完全保留,同时实现不区分大小写的模糊搜索,适配各种关键词(像"mus"、"tang"、"mustang"都能匹配)。

完整解决方案代码

function filterNestedArray(originalArray, searchKeyword) {
  // 统一转小写,实现不区分大小写的模糊匹配
  const lowerCaseKeyword = searchKeyword.toLowerCase();
  
  return originalArray.map(parentElement => {
    // 过滤当前父元素的data数组,只保留nome包含关键词的子项
    const filteredSubItems = parentElement.data.filter(subItem => 
      subItem.nome.toLowerCase().includes(lowerCaseKeyword)
    );
    
    // 复制原父元素的所有属性,仅替换data字段,保留原结构
    return { ...parentElement, data: filteredSubItems };
  });
}

测试用例验证

测试场景1:单父元素,模糊搜索关键词

const array1 = [{ "title": "Carros", "data" : [{ "nome": "Mustang" }, {"nome": "Camaro"}]}];
console.log(filterNestedArray(array1, "mus"));
// 输出:[{ "title": "Carros", "data" : [{ "nome": "Mustang" }]}]

测试场景2:多父元素,仅匹配其中一个的子项

const array2 = [{ "title": "Carros", "data" : [{ "nome": "Mustang" }]}, { "title": "Motos", "data" : [{ "nome": "Yamaha" }]}];
console.log(filterNestedArray(array2, "mustang"));
// 输出:[{ "title": "Carros", "data" : [{ "nome": "Mustang" }]}, { "title": "Motos", "data" : [] }]

为什么这个方案有效?

  • 模糊匹配更灵活:把关键词和子项的nome都转成小写,用includes方法实现模糊搜索,不管关键词大小写、长短都能匹配。
  • 严格保留原结构:用扩展运算符{ ...parentElement, data: filteredSubItems }复制原父元素的所有属性,只替换data字段,不会像原代码那样新增多余的nome属性。
  • 适配多父元素场景:遍历每个父元素单独处理data,没匹配到子项的父元素自然返回空数组,完全符合你的需求。

内容的提问来源于stack exchange,提问作者Vélcis Ribeiro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:21:13