首页 > 解决方案 > 使用 Angular Material 将带有嵌套子级的 Json 转换为树结构

问题描述

下面是我从服务器获得的 Json,我使用角度材料树创建了一个树结构

使用角度材料输出后,我得到的是

>country_1
    >state_A
        >0
          2es34Sdsre332
          222kms
          ABC
        >1
          id4es34Sdsre332
          1232kms
          BCD
    >state_B
        >0
          3es34Sdsre332
          45232kms
          PQR
        >1
          5es34Sdsre332
          3232kms
          LMN
>country_2
    >state_X
        >0
          4rtr34Sdsre332
          2232kms
          ABCD
        >1
          3es34Sdsre332
          1232kms
          BCDED
    >state_Y
        >0
          id7ys34Sdsre332
          45232kms
          PQRE
        >1
          6ues34Sdsre332
          3232kms
          LMNRE 

我期待输出

>country_1
    >state_A
        ABC
        BCD
    >state_B
        PQR
        LMN
>country_2
    >state_X
        ABCD
        BCDED
    >state_Y
        PQRE
        LMNRE

我正在使用角度材料示例来构造树,并使用 buidtree 方法来构造文件节点

  buildFileTree(obj: {[key: string]: any}, level: number): FileNode[] {
    return Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {
      const value = obj[key];
      const node = new FileNode();
      node.filename = key;
      if (value != null) {
        if (typeof value === 'object') {
          node.children = this.buildFileTree(value, level + 1);
          // console.log(node.children);
        } else {
          node.type = value;
        }
      }
      return accumulator.concat(node);
    }, []);
  }

标签: angularangular-material-6

解决方案


推荐阅读