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

如何遍历JavaScript对象至指定第n层级?

嘿,这个需求我经常碰到,刚好有两种实用的实现方式,不管你是喜欢直观的递归,还是担心深嵌套栈溢出的迭代,都能搞定精准遍历到指定第n层级的需求。

方法一:递归遍历(直观好理解)

递归是最直接的思路,核心就是跟踪当前遍历的层级,每深入一层就把层级数+1,当达到目标层级n时,就停止往下钻,只处理当前层级的节点。

举个结合你示例对象的代码例子:

// 你的示例对象
const sampleObj = {
  "sampleA": {
    "sampleB1": {
      "sampleC1": {
        "sample1": "sample",
        "sample2": "sample",
        "sample3": "sample",
        "sample4": "sample",
        "sample5": "sample"
      }
    },
    "sampleB2": {
      "sample1": "sample",
      "sample2": "sample sample",
      "sample3": "sample",
      "sample4": "sample sample",
      "sample5": "sample sample",
      "sample6": "sample"
    },
    "sampleB3": {
      "sample1": "sample",
      "sample2": "sample sample",
      "sample3": "sample sample",
      "sample4": "sample sample",
      "sample5": {
        "sample6": "sample",
        "sample7": "sample sample"
      }
    }
  }
};

// 递归遍历函数
function traverseRecursively(obj, currentLevel = 1, targetLevel, callback) {
  // 处理当前层级的所有键值对
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      // 调用回调处理当前节点,你可以自定义逻辑(比如打印、收集数据)
      callback(key, obj[key], currentLevel);
      
      // 如果还没到目标层级,且当前值是有效对象(排除null,因为typeof null是object),继续递归
      if (currentLevel < targetLevel && typeof obj[key] === 'object' && obj[key] !== null) {
        traverseRecursively(obj[key], currentLevel + 1, targetLevel, callback);
      }
    }
  }
}

// 调用示例:遍历到第3层(sampleC1及同级节点)
console.log('遍历到第3层的结果:');
traverseRecursively(sampleObj, 1, 3, (key, value, level) => {
  console.log(`层级${level}:${key} = ${typeof value === 'object' ? '[Object]' : value}`);
});

这里的层级计数可以灵活调整——比如你要是把最外层算第0层,把currentLevel初始值改成0就行。

方法二:迭代遍历(避免深嵌套栈溢出)

如果你的对象嵌套特别深(比如几十上百层),递归可能会触发Maximum call stack size exceeded错误,这时候迭代方式就更安全了。我们可以用队列(或栈)存储待处理的节点和对应层级,循环处理队列元素:

function traverseIteratively(obj, targetLevel) {
  // 队列元素格式:[当前对象, 当前层级]
  const queue = [[obj, 1]];
  
  while (queue.length > 0) {
    const [currentObj, currentLevel] = queue.shift();
    
    for (const key in currentObj) {
      if (currentObj.hasOwnProperty(key)) {
        const value = currentObj[key];
        console.log(`层级${currentLevel}:${key} = ${typeof value === 'object' && value !== null ? '[Object]' : value}`);
        
        // 未到目标层级且是有效对象,就加入队列,层级+1
        if (currentLevel < targetLevel && typeof value === 'object' && value !== null) {
          queue.push([value, currentLevel + 1]);
        }
      }
    }
  }
}

// 调用示例:遍历到第2层(sampleB1/B2/B3及同级节点)
console.log('\n遍历到第2层的结果:');
traverseIteratively(sampleObj, 2);

这个代码用队列实现的是广度优先遍历(先处理同一层级所有节点,再往下),如果想要深度优先遍历,把shift()改成pop()就行,非常灵活。

额外注意点
  • 必须判断obj[key] !== null,不然会把null当成对象继续遍历,引发错误;
  • 如果你需要收集遍历结果而非打印,把回调函数改成数据收集逻辑即可(比如把节点信息push到数组);
  • 最好给目标层级n加个合法性判断,比如n < 1时直接返回或提示错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:52:48