我有一个看起来像这样的对象数组:
[{ 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/