在JavaScript中将文件/目录结构转换为“树”

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

[{ 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' }] 

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

我想要做的是确定这些的“根”节点。 最终,这将被存储在MongoDB中,并使用物化path来确定它的关系。

在这个例子中, /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: {} } } } } } } } } 

假设/将永远不会出现在文件列表中,像这样的事情应该工作:

 function treeify(files) { var path = require('path') files = files.reduce(function(tree, f) { var dir = path.dirname(f.path) if (tree[dir]) { tree[dir].children.push(f) } else { tree[dir] = { implied: true, children: [f] } } if (tree[f.path]) { f.children = tree[f.path].children } else { f.children = [] } return (tree[f.path] = f), tree }, {}) return Object.keys(files).reduce(function(tree, f) { if (files[f].implied) { return tree.concat(files[f].children) } return tree }, []) } 

它会把你在问题中提到的数组变成这样的东西:

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

我没有真正用其他数据源来testing这个,所以你的milage可能会有所不同,但至less应该让你朝正确的方向发展。