本文介绍如何使用纯 javascript(vanilla js)将深度嵌套的 json 文件树对象(键为路径名、值为子对象或 null)递归转换为符合树视图组件要求的标准格式,包含完整可运行函数、执行逻辑说明与关键注意事项。
针对键代表路径名、值为子对象或 null 的深度嵌套 json 文件树对象,本文以纯 javascript(vanilla js)递归整理为树视图组件接受的标准格式,同时说明关键注意事项、执行逻辑,并提供完整可运行函数。
后端可能以对象嵌套表达目录层级,并用 null 标记文件;前端开发要把这类扁平化路径映射结构交给 Ant Design Tree、Vue TreeView 或自研 UI 组件,就须整理成标准化节点格式,其中 label(显示名)与 path(唯一路径)为必备字段,children 数组则按需提供。
原始数据以 / 为根,其子属性分别表示子目录或文件:值为 null 时,键代表文件;值为对象时,键代表子目录。转换后的每个节点需要明确携带 path,并且只有存在子项时才设置 children 数组。
下面给出一种高效且不存在递归调用栈风险的迭代式转换函数(以栈完成递归模拟),适用于 Vanilla JS 环境:
function convertFileTreeToTreeView(fileTree) { // 初始化根节点:label 为 "/",children 为空数组 const root = { label: "/", children: [] }; // 使用栈保存待处理的 [父节点, 当前层级对象] 元组 const stack = [[root, fileTree]]; while (stack.length > 0) { const [parent, node] = stack.pop(); // 遍历当前层级所有条目(目录名或文件名) for (const [key, value] of Object.entries(node)) { // 构造当前项完整路径 const path = parent.path ? `${parent.path}/${key}` : `/${key}`; if (value === null) { // 值为 null → 视为文件节点,仅需 label 和 path parent.children.push({ label: key, path }); } else { // 值为对象 → 视为目录节点,需创建 children 数组并入栈处理 const childNode = { label: key, path, children: [] }; parent.children.push(childNode); stack.push([childNode, value]); } } } return root;}
✅ 使用示例:
const inputTree = { "/": { "apps": { "text-open": { "app.js": null }, "html-open": { "app.js": null }, "editor": { "app.js": null, "index.html": null } }, "Images": { "image.png": null }, "Documents": { "README.txt": null, "example.txt": null } }};const treeViewData = convertFileTreeToTreeView(inputTree["/"]);console.log(JSON.stringify(treeViewData, null, 2));// 输出即为目标格式(含完整 path 和嵌套 children)
⚠️ 注意事项:
整体方案无依赖且简洁健壮,能够直接接入任意现代浏览器环境,适合作为连接数据层和树形 UI 的胶水函数。