javascript 将文件路径列表转换为ReactJS中的json

v64noz0r  于 2023-02-28  发布在  Java
关注(0)|答案(2)|浏览(115)

我正在尝试构建一个函数,将路径列表转换为对象,如下所示;脚本的输出应按如下结构进行。
产出

data = [
{
    "type": "folder",
    "name": "dir1",
    "children": [
        {
            "type": "folder",
            "name": "photos",
            "children": [
                {
                    "type": "file",
                    "name": "mydir1.pdf",
                },
                {
                    "type": "file",
                    "name": "yourdir1.pdf",
                }
            ]
        }
    ]
}

输入是这样的

paths = [
        "dir1/photos/mydir1.pdf",
        "dir1/photos/yourdir1.pdf"
    ]
0sgqnhkj

0sgqnhkj1#

您可以尝试以下功能:

function buildTree(paths) {
  const tree = [];
  
  for (let path of paths) {
    const pathParts = path.split('/');
    let subtree = tree;
    
    for (let i = 0; i < pathParts.length; i++) {
      const part = pathParts[i];
      const isFolder = i < pathParts.length - 1;
      
      let node = subtree.find(n => n.name === part);
      
      if (!node) {
        node = {
          type: isFolder ? 'folder' : 'file',
          name: part,
          children: isFolder ? [] : undefined
        };
        
        subtree.push(node);
      }
      
      if (isFolder) {
        subtree = node.children;
      }
    }
  }
  
  return tree;
}
6rvt4ljy

6rvt4ljy2#

可以借助对象引用来构建树。

const final = {result: []};
    
for (const path of paths) {
  let context = final;
  
  for (const name of path.split("/")) {
    if (!context[name]) {
      context[name] = { result: [] };
      let type = "folder";
      if (name.endsWith(".pdf")) {
        type = "file";
      }
      context.result.push({name, type, children: context[name].result})
    }
    
    context = context[name];
  }
}

console.log(final.result)

相关问题