Angular材质树形视图的数据处理

问题描述

我正在尝试使用递归函数来处理数据,以使用角度材质树视图在树视图中显示数据。

我想转换为的数据格式:

export class TreeNode {
  constructor(name,id,children = []) {
    this.name = name;
    this.id = id;
    this.children = children;
  }
  name: string;
  id: number;
  children: TreeNode[] = []; depth can be maximum 5;
}

我拥有的数据的格式如下:

[{
    description: "des",id: 43,childCenters: [{
         description: "des",// this should be name of TreeNode
         id: 1,// this should be id
         childCenters[{
             // and so on
         }],consultants:[
             name:"cname",// this should be name
             id: 2 // this should be id
         ]
    }],consultants:[
         name:"cname",// this should be name
         id: 2 // this should be id
    ]
}]

我用于转换的代码如下:

this.buildTreeNode(data); // data is raw data
buildTreeNode(list,isChildren = false) {
    for(const currentNode of list) {
      let newNode = new TreeNode(currentNode.description,currentNode.id,[])
      if (currentNode.childCenters.length === 0) {
        let arr = this.buildConsultantTreeNode(currentNode);
        arr.forEach(data => {
          newNode.children.push(data);
        })
        if (!isChildren) {
          this.sampleDataSource.push(newNode);
        } else {
          return newNode;
        }
      } else {
        currentNode.childCenters.forEach(childNode => {
          let childTreeNode = new TreeNode(childNode.description,childNode.id,[]);
          if (!(childNode.childCenters.length == 0)) {
            const data = this.buildTreeNode(childNode.childCenters,true); // used recursion here.
            childTreeNode.children.push(data);
          } 
          let arr = this.buildConsultantTreeNode(childNode);
          arr.forEach(data => {
            childTreeNode.children.push(data);
          })
          newNode.children.push(childTreeNode);
        });
        let arr = this.buildConsultantTreeNode(currentNode);
        arr.forEach(data => {
          newNode.children.push(data);
        })
      }
      if (!isChildren) {
        this.sampleDataSource.push(newNode);
        return newNode;
      } else {
        return newNode;
      }
    }
  }

  buildConsultantTreeNode(node) {
    node.consultants.sort(function (a,b) {
      if (a.name < b.name) { return -1; }
      if (a.name > b.name) { return 1; }
      return 0;
    });
    let arr: TreeNode[] = []
    node.consultants.forEach(c => {
      if (c.profitCenterId) {
        c.parentProfitCenterId = c.profitCenterId;
      }
      const data = new TreeNode(c.name,c.id,[]);

      arr.push(data);
    });
    return arr;
  }

但是代码最多只能达到2个级别,任何帮助将不胜感激。 预先感谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)