如何在JavaScript中递归转换嵌套对象为指定树形结构?
递归转换嵌套对象为层级结构
问题描述
现有如下嵌套对象:
const path = { "posts": { "backend": { "a.mdx": "./pages/posts/backend/a.mdx" }, "frontend": {}, "retrospective": { "b.mdx": "./pages/posts/retrospective/b.mdx", "c.mdx": "./pages/posts/retrospective/c.mdx", "d.mdx": "./pages/posts/retrospective/d.mdx" } } };
需要将其转换为以下层级数组结构:
const path = [{ title: 'posts', sub: [ { title: 'backend', sub: [ { title: 'a.mdx', path: './pages/posts/backend/a.mdx' }, ], }, { title: 'frontend', sub: [], }, { title: 'retrospective', sub: [ { title: 'b.mdx', path: './pages/posts/retrospective/b.mdx' }, { title: 'c.mdx', path: './pages/posts/retrospective/c.mdx' }, { title: 'd.mdx', path: './pages/posts/retrospective/d.mdx' }, ], }, ], }];
请问如何通过递归实现这种结构转换?查阅lodash库文档后未找到合适的组合方法,求实现思路及代码。
实现思路
核心逻辑是递归遍历对象的每一层键值对,根据值的类型生成对应结构:
- 若当前值是字符串(对应文件路径):生成包含
title(键名)和path(值)的对象。 - 若当前值是对象:生成包含
title(键名)和sub(递归处理该子对象得到的数组)的对象。 - 空对象会自动生成
sub: []的结构,无需额外处理。
代码实现
function transformNestedObj(obj) { return Object.entries(obj).map(([key, value]) => { // 处理文件路径(字符串值) if (typeof value === 'string') { return { title: key, path: value }; } // 递归处理子目录(对象值) return { title: key, sub: transformNestedObj(value) }; }); } // 调用示例 const originalPath = { "posts": { "backend": { "a.mdx": "./pages/posts/backend/a.mdx" }, "frontend": {}, "retrospective": { "b.mdx": "./pages/posts/retrospective/b.mdx", "c.mdx": "./pages/posts/retrospective/c.mdx", "d.mdx": "./pages/posts/retrospective/d.mdx" } } }; const transformedPath = transformNestedObj(originalPath); console.log(transformedPath);
执行这段代码后,会直接输出你期望的层级结构,空目录frontend会自动生成sub: [],完全匹配需求。
内容的提问来源于stack exchange,提问作者togong
相关产品推荐
相关产品推荐

