[英]How to transform array of strings into specific tree structure in Javascript
I get a list of file paths from the backend, it represents a folder structure and looks like this:我从后端得到一个文件路径列表,它代表一个文件夹结构,如下所示:
paths = ["path/to/file1.doc", "path/to/file2.doc", "foo/bar.doc]
The lengths of the paths are arbitrary.路径的长度是任意的。 In order to use a file tree component ( angular2-tree-component ) I need to transform this data into the following format :
为了使用文件树组件( angular2-tree-component ),我需要将此数据转换为以下格式:
nodes = [
{
"name": "path",
"children": [
{
"name": "to",
"children": [
{"name": "file1.doc"},
{"name": "file2.doc"}
]
}
]
},
{
"name": "foo",
"children": [
{"name": "bar.doc"}
]
}
]
I think the most efficient way to transform the data is to我认为转换数据的最有效方法是
Step one:步骤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;
}
When passing "nodes" into the transformToTree function (transformToTree(nodes)), I get the following result:将“节点”传递到 transformToTree 函数 (transformToTree(nodes)) 时,我得到以下结果:
{
"path": {
"to": {
"file1.doc": {},
"file2.doc": {}
}
},
"foo": {
"bar": {}
}
}
I don't know how to proceed from here = how to iterate over all the keys and values while building the final array in the required structure.我不知道如何从这里开始=如何在所需结构中构建最终数组时迭代所有键和值。
There are a few examples like this or that on SO, but I was not able to understand how I could adapt them to my needs.在 SO 上有一些这样或那样的例子,但我无法理解如何使它们适应我的需求。
I would go with two nested loops, one for pathes and one for the splitted names and find the name or create new objects.我会使用两个嵌套循环,一个用于路径,一个用于拆分名称,然后查找名称或创建新对象。
var paths = ["path/to/file1.doc", "path/to/file2.doc", "foo/bar.doc"], result = []; paths.reduce((r, path) => { path.split('/').reduce((o, name) => { var temp = (o.children = o.children || []).find(q => q.name === name); if (!temp) o.children.push(temp = { name }); return temp; }, r); return r; }, { children: result }); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.