我有 treeFlatNode 数组,我想以树格式构建它。或者我可以直接以 Angular 在树中显示这个数组吗?
data=[
{
expandable: true
level: 0
name: "2021-12-31"
path: null
},
{
expandable: false
level: 2
name: "A.txt"
path: "2021-12-31/B/C/A.txt"
}
]
required format
tree=[
name:"2021-12-03",
children:[
name:"B",
children:[{
name:"C"
children:[{
name:"A.txt"
children:[]
}]
}]
]
]
最佳答案
您可以使用一个对象 (map
) 将(子)路径映射到最终树中的节点。如果尚不存在,则会将其添加到父级的子级中。
由于您的树结构实际上代表一个森林(可以有多个根),因此我将结果变量命名为 forest
而不是 tree
片段:
function toForest(data) {
const roots = [];
const map = {};
for (const obj of data) {
let key = "";
let children = roots;
for (const name of (obj.path ?? obj.name).split("/")) {
let child = map[key += "/" + name];
if (!child) children.push(map[key] = child = { name, children: [] });
({children} = child);
}
}
return roots;
}
// Example run
let data = [{expandable: true,level: 0,name: "2021-12-31",path: null}, {expandable: false,level: 2,name: "A.txt",path: "2021-12-31/B/C/A.txt"}];
let forest = toForest(data);
console.log(forest);
关于javascript - 如何从 flatTreeNode 填充树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70575133/