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

如何使用.filter方法过滤5层嵌套的对象数组?

处理5层嵌套对象数组的.filter过滤方案

嘿,我来帮你搞定这个5层嵌套数组的过滤问题!这种多层嵌套的结构直接用普通的filter确实容易懵——因为如果只过滤最外层,内层不满足条件的元素还会留在里面;反之如果只处理内层,外层的结构又会丢失。所以我们需要逐层遍历+递归过滤,同时保留符合条件的层级结构。

假设你的需求是:过滤出所有包含id_client为"rabbit"的完整嵌套分支(也就是只要最内层Object4List里有符合条件的元素,就保留它上层的所有父级对象),下面是具体的实现代码:

var objList = [
  {
    "name": "Object0Name",
    "id": "Object0ID",
    "Object1List": [
      {
        "id": "Object1id_A1",
        "name": "Object1Name_A1",
        "Object2List": [
          {
            "id": 187,
            "name": "Object2Name_A1",
            "Object3List": [
              {
                "id": "mammal",
                "name": "mammal",
                "Object4List": [
                  { "id_client": "rabbit", "Currency": "EUR" },
                  { "id_client": "cat", "Currency": "EUR" },
                  { "id_client": "tiger", "Currency": "EUR" }
                ]
              }
            ]
          }
        ]
      },
      {
        "id": "Object1id_B1",
        "name": "Object1Name_B1",
        "Object2List": [
          // 可添加其他测试数据
        ]
      }
    ]
  }
];

// 定义递归过滤函数
function filterNestedArray(data) {
  // 处理最内层的Object4List
  if (data.Object4List) {
    const filtered4 = data.Object4List.filter(item => item.id_client === "rabbit");
    // 有符合条件的元素则保留该层,否则返回null标记为待过滤分支
    return filtered4.length > 0 ? { ...data, Object4List: filtered4 } : null;
  }
  // 处理Object3List
  if (data.Object3List) {
    const filtered3 = data.Object3List.map(filterNestedArray).filter(Boolean);
    return filtered3.length > 0 ? { ...data, Object3List: filtered3 } : null;
  }
  // 处理Object2List
  if (data.Object2List) {
    const filtered2 = data.Object2List.map(filterNestedArray).filter(Boolean);
    return filtered2.length > 0 ? { ...data, Object2List: filtered2 } : null;
  }
  // 处理Object1List
  if (data.Object1List) {
    const filtered1 = data.Object1List.map(filterNestedArray).filter(Boolean);
    return filtered1.length > 0 ? { ...data, Object1List: filtered1 } : null;
  }
  // 处理最外层数组
  return data.map(filterNestedArray).filter(Boolean);
}

// 执行过滤并输出结果
const filteredResult = filterNestedArray(objList);
console.log(filteredResult);

代码说明:

  • 递归函数从最内层(Object4List)往上逐层处理,确保只有包含符合条件子元素的分支才会被保留;
  • 使用{ ...data, [key]: filtered }复制原对象并替换过滤后的数组,避免修改原始数据;
  • 用filter(Boolean)自动过滤掉返回null的空分支,保证最终结果只保留有效层级。

如果你的过滤条件不同(比如过滤Currency为特定值,或者多条件组合),只需要修改最内层的过滤判断即可:

// 示例:过滤Currency为"EUR"且id_client不是"tiger"的元素
const filtered4 = data.Object4List.filter(item => item.Currency === "EUR" && item.id_client !== "tiger");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:39:40