如何在无数组的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
相关产品推荐
相关产品推荐

