javascript - 在javascript中将文件/目录结构转换为 'tree'

标签 javascript node.js tree

我有一个看起来像这样的对象数组:

[{ name: 'test',
  size: 0,
  type: 'directory',
  path: '/storage/test' },
{ name: 'asdf',
  size: 170,
  type: 'directory',
  path: '/storage/test/asdf' },
{ name: '2.txt',
  size: 0,
  type: 'file',
  path: '/storage/test/asdf/2.txt' }]

可以有任意数量的任意路径,这是遍历目录中的文件和文件夹的结果。

我要做的是确定这些的“根” Node 。最终,这将存储在 mongodb 中并使用物化路径来确定它的关系。

在此示例中,/storage/test 是没有父级的根。 /storage/test/asdf 具有 /storage/test 的父级,它是 /storage/test/asdf/2.txt 的父级.

我的问题是,您将如何遍历此数组以确定父项和关联的子项?任何正确方向的帮助都会很棒!

谢谢

最佳答案

你可以这样做:

var arr = [] //your array;
var tree = {};

function addnode(obj){
  var splitpath = obj.path.replace(/^\/|\/$/g, "").split('/');
  var ptr = tree;
  for (i=0;i<splitpath.length;i++)
  {
    node = { name: splitpath[i],
    type: 'directory'};
    if(i == splitpath.length-1)
    {node.size = obj.size;node.type = obj.type;}
    ptr[splitpath[i]] = ptr[splitpath[i]]||node;
    ptr[splitpath[i]].children=ptr[splitpath[i]].children||{};
    ptr=ptr[splitpath[i]].children;
  }    
}

arr.map(addnode);
console.log(require('util').inspect(tree, {depth:null}));

输出

{ storage:
   { name: 'storage',
     type: 'directory',
     children:
      { test:
         { name: 'test',
           type: 'directory',
           size: 0,
           children:
            { asdf:
               { name: 'asdf',
                 type: 'directory',
                 size: 170,
                 children: { '2.txt': { name: '2.txt', type: 'file', size: 0, children: {} } } } } } } } }

关于javascript - 在javascript中将文件/目录结构转换为 'tree',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19531453/

相关文章:

javascript - 如何获取元素位置,如果它以 `margin:auto` 为中心

javascript - 使未选中的 HTML 复选框提交选中的值

node.js - 来自 Mongoose 的流数据 - "Can' t 在发送后设置 header ”

javascript - 类别子类别树问题 javascript

algorithm - 在 Neo4j 中查找树的最长分支

javascript - 在 IE8 中查看时图像被压扁

javascript - 影子dom内的脚本不起作用

node.js - 当定向到文件时,如何从 Nodejs 中的 stdout 刷新管道输出

node.js - Node - 递归搜索依赖关系

java - GWT:更改树行的填充?