You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用原生JS将文件树格式转换为TreeView组件所需格式?

原生JS实现文件树结构转换方案

原始文件树格式

{
  "/": {
    "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
    }
  }
}

TreeView目标格式

{
  label: "/", children: [
    {label: "apps", path: "/apps", children: [
      {label: "text-open", path: "/apps/text-open", children: [
        {label: "app.js", path: "/apps/text-open/app.js"},
      ]},
      {label: "html-open", path: "/apps/html-open", children: [
        {label: "app.js", path: "/apps/html-open/app.js"},
      ]},
       {label: "editor", path: "/apps/editor", children: [
        {label: "app.js", path: "/apps/editor/app.js"},
        {label: "index.html", path: "/apps/editor/index.html"},
      ]},
    ]},
    {label: "Documents", path: "/Documents", children: [
      {label: "README.txt", path: "/Documents/README.txt"},
      {label: "example.txt", path: "/Documents/example.txt"},
    ]},
    {label: "Images", path: "/Images", children: [
      {label: "image.png", path: "/Images/image.png"},
    ]},
  ],
}

转换实现代码

使用递归处理嵌套结构,代码如下:

function convertFileTree(originalTree) {
  // 递归处理节点的函数
  function processNode(node, currentPath) {
    const children = [];
    // 遍历当前节点的所有子项
    for (const key of Object.keys(node)) {
      const newPath = currentPath === "/" ? `/${key}` : `${currentPath}/${key}`;
      if (node[key] === null) {
        // 处理文件:无children属性
        children.push({
          label: key,
          path: newPath
        });
      } else {
        // 处理文件夹:递归生成children
        children.push({
          label: key,
          path: newPath,
          children: processNode(node[key], newPath)
        });
      }
    }
    return children;
  }

  // 获取根节点(原始结构中只有"/"一个根键)
  const rootKey = Object.keys(originalTree)[0];
  return {
    label: rootKey,
    children: processNode(originalTree[rootKey], rootKey)
  };
}

// 使用示例
const originalTree = {
  "/": {
    "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 = convertFileTree(originalTree);
console.log(treeViewData);

代码说明

  1. 递归核心逻辑:processNode函数负责处理单个节点,根据子项是文件(值为null)还是文件夹(值为对象)生成对应结构。
  2. 路径拼接:根据当前路径和子项名称拼接完整路径,根路径特殊处理避免出现//。
  3. 根节点处理:提取原始结构中的根键(固定为"/"),生成TreeView需要的根节点结构。

内容的提问来源于stack exchange,提问作者Bobson Tobson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 20:04:54