JavaScript获取对象键路径:实现深度遍历获取键路径与对应值
解决方案
可以写一个递归遍历函数,在遍历过程中跟踪当前的键路径和深度,遇到非对象类型的值时,就把路径、值、深度收集到结果数组里。
示例代码
function deepTraverse(obj) { const result = []; function traverse(currentObj, currentPath = [], depth = 0) { // 遍历当前对象的所有键 for (const key of Object.keys(currentObj)) { const newPath = [...currentPath, key]; const newValue = currentObj[key]; const newDepth = depth + 1; // 判断当前值是否是纯对象(排除null和数组,需处理数组可调整条件) if (typeof newValue === 'object' && newValue !== null && !Array.isArray(newValue)) { // 递归遍历子对象 traverse(newValue, newPath, newDepth); } else { // 非对象值,收集结果 result.push({ path: newPath.join('.'), // 用点连接成路径字符串,也可保留数组形式 value: newValue, depth: newDepth }); } } } traverse(obj); return result; } // 测试用例 const input = { tree1: { node1: 'valOfnode1', node2: { subNode1: 123, subNode2: true } }, tree2: 'directValue' }; console.log(deepTraverse(input));
输出结果
[ { path: 'tree1.node1', value: 'valOfnode1', depth: 2 }, { path: 'tree1.node2.subNode1', value: 123, depth: 3 }, { path: 'tree1.node2.subNode2', value: true, depth: 3 }, { path: 'tree2', value: 'directValue', depth: 1 } ]
代码说明
traverse是内部递归函数,接收当前遍历对象、当前键路径数组、当前深度三个参数。- 每次遍历键时,生成新的路径数组和深度(初始深度为0,每深入一层加1)。
- 判断当前值是否为纯对象,若是则递归遍历;否则将结果存入数组。
- 路径可选择数组形式(如
['tree1', 'node1'])或点连接的字符串,按需调整即可。
如果需要支持数组遍历,只需修改判断条件,将数组纳入递归处理:
// 修改判断条件,数组也递归遍历 if (typeof newValue === 'object' && newValue !== null) { traverse(newValue, newPath, newDepth); }
此时输入 { arr: [1, { nested: 'test' }] } 会输出:
[ { path: 'arr.0', value: 1, depth: 2 }, { path: 'arr.1.nested', value: 'test', depth: 3 } ]
内容的提问来源于stack exchange,提问作者Sabir
相关产品推荐
相关产品推荐

