javascript - 如何从 flatTreeNode 填充树?

标签 javascript angular tree treeview

我有 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/

相关文章:

javascript - 单击父按钮单击时如何重置子输入的数据和 View ?

tree - 更新一个 dijit treeWidget 节点属性

html - 为什么html中没有树标签?

php - JS 创建的表单元素未提交

javascript - Mobile Safari - JavaScript 单击事件中断复制和粘贴

javascript - Chrome 和 IE 中的自签名证书问题,但在 Firefox 中正常

angular - 在 Angular8 的动态 View 中添加友好的 Url 以使用 SEO

javascript - 使用 Mapbox 读取本地 geojson 文件

angular - 在 Angular 2 应用程序上使用 Google Adsense 广告

c++ - 'Head First' 风格的数据结构和算法书?