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

dzm*_*dzm 6 javascript tree node.js

我有一个对象数组,如下所示:

[{ 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' }]
Run Code Online (Sandbox Code Playgroud)

可以有任意数量的任意路径,这是迭代目录中的文件和文件夹的结果.

我要做的是确定这些的"根"节点.最终,这将存储在mongodb中并使用物化路径来确定它的关系.

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

我的问题是,你将如何迭代这个数组,以确定父母和相关的孩子?任何正确方向的帮助都会很棒!

谢谢

use*_*109 9

你可以这样做:

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}));
Run Code Online (Sandbox Code Playgroud)

产量

{ 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: {} } } } } } } } }
Run Code Online (Sandbox Code Playgroud)