如何获取JavaScript嵌套JSON对象含数组索引的所有属性完整路径
问题原因
原有代码无法生成完整路径的核心问题是递归时没有向上层传递父路径前缀,同时没有针对数组和对象的输出规则做区分,导致只能打印当前层级的键名,无法拼接出带层级、带数组索引的完整路径。
修复后代码
function printAllPaths(node, parentPath = '') { // 处理数组:数组索引仅作为路径拼接段,不单独打印索引路径 if (Array.isArray(node)) { node.forEach((item, index) => { const currentPath = parentPath ? `${parentPath}.${index}` : `${index}`; if (typeof item === 'object' && item !== null) { printAllPaths(item, currentPath); } }); return; } // 处理普通对象:所有对象键都打印对应完整路径 if (typeof node === 'object' && node !== null) { for (const key in node) { const currentPath = parentPath ? `${parentPath}.${key}` : key; console.log(currentPath); const value = node[key]; if (typeof value === 'object' && value !== null) { printAllPaths(value, currentPath); } } } } // 调用示例 const target = { "gender": "man", "jobinfo": { "type": "teacher" }, "children": [ { "name": "Daniel", "age": 12, "pets": [ { "type": "cat", "name": "Willy", "age": 2 }, { "type": "dog", "name": "Jimmie", "age": 5 } ] } ] }; printAllPaths(target);
输出说明
运行上述代码输出的路径和预期路径完全一致:
gender jobinfo jobinfo.type children children.0.name children.0.age children.0.pets children.0.pets.0.type children.0.pets.0.name children.0.pets.0.age children.0.pets.1.type children.0.pets.1.name children.0.pets.1.age
示例里部分行尾带的逗号属于额外格式要求,如果需要复现该格式,只需要把打印语句改成console.log(currentPath + ',')即可。代码额外增加了null值判断,避免typeof null === 'object'导致的运行报错。
内容的提问来源于stack exchange,提问作者Arrstad
相关产品推荐
相关产品推荐

