我从后端获取文件路径列表,它代表文件夹结构,如下所示:
paths = ["path/to/file1.doc", "path/to/file2.doc", "foo/bar.doc]
路径的长度是任意的。为了使用文件树组件(角度2树组件 https://github.com/500tech/angular-tree-component)我需要将这些数据转换为以下格式 https://angular2-tree.readme.io/docs/options-1:
nodes = [
{
"name": "path",
"children": [
{
"name": "to",
"children": [
{"name": "file1.doc"},
{"name": "file2.doc"}
]
}
]
},
{
"name": "foo",
"children": [
{"name": "bar.doc"}
]
}
]
I think转换数据最有效的方法是
- 首先将数组与镜像树结构的文件映射到
- 迭代每个键以最终确定“子/父”关系。
步骤1:
transformToTree(data) {
const tree = {};
function addPathsToTree(paths) {
let map = tree
paths.forEach(function(item) {
map[item] = map[item] || {};
map = map[item];
});
}
data.forEach(function(path) {
let pathPart = path.split('/');
addPathsToTree(pathPart);
});
return pathTree;
}
当将“节点”传递到transformToTree函数(transformToTree(nodes))时,我得到以下结果:
{
"path": {
"to": {
"file1.doc": {},
"file2.doc": {}
}
},
"foo": {
"bar": {}
}
}
我不知道如何从这里继续=如何在所需结构中构建最终数组时迭代所有键和值。
有几个例子,例如this https://stackoverflow.com/questions/47062922/how-to-get-all-keys-with-values-from-nested-objects/47063174 or that https://stackoverflow.com/questions/8085004/iterate-through-nested-javascript-objectsSO,但我无法理解如何使它们适应我的需求。