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

如何在无数组的JS深层嵌套对象中获取目标key及各级父级路径

实现思路

递归遍历对象时携带当前已遍历的父级key路径,匹配到目标key后直接按要求顺序拼接路径即可,相比原代码改用for...of遍历可以在找到目标后提前终止,减少无效遍历。

可直接运行的修改后代码

var data = {
  bar: 'a',
  child: {
    b: 'b',
    grand: {
      greatgrand: {
        c: 'c'
      }
    }
  }
};

let arr = [];

const findParentGrandparent = (obj, target, parentPath = []) => {
  for (const [key, value] of Object.entries(obj)) {
    // 匹配到目标key,直接按要求顺序生成结果
    if (key === target) {
      arr = [key, ...parentPath];
      return;
    }
    // 排除null的情况,因为typeof null也会返回object
    if (typeof value === 'object' && value !== null) {
      // 递归下一层,把当前key加入父级路径
      findParentGrandparent(value, target, [key, ...parentPath]);
    }
  }
};

// 测试用例
findParentGrandparent(data, 'c');
console.log(arr); // 输出 ['c', 'greatgrand', 'grand', 'child']

findParentGrandparent(data, 'greatgrand');
console.log(arr); // 输出 ['greatgrand', 'grand', 'child']

优化版纯函数实现(无外部依赖)

如果不想依赖外部的arr变量,可以改成纯函数直接返回路径结果:

const findKeyPath = (obj, target, parentPath = []) => {
  for (const [key, value] of Object.entries(obj)) {
    if (key === target) {
      return [key, ...parentPath];
    }
    if (typeof value === 'object' && value !== null) {
      const found = findKeyPath(value, target, [key, ...parentPath]);
      if (found) return found;
    }
  }
  return []; // 未匹配到目标时返回空数组
};

// 测试用例
console.log(findKeyPath(data, 'c')); // ['c', 'greatgrand', 'grand', 'child']
console.log(findKeyPath(data, 'greatgrand')); // ['greatgrand', 'grand', 'child']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 15:51:01