как построить новый объект, основанный на другом объекте динамически - PullRequest
0 голосов
/ 03 августа 2020

Я реализую древовидную структуру для моего пользовательского интерфейса с деревом материалов, в котором потребуется новый объект для этого дерева. этот объект выглядит так:

[
  {
    name: 'Fruit',
    children: [
      {name: 'Apple'},
      {name: 'Banana'},
      {name: 'Fruit loops'},
    ]
  }
]

, но теперь то, что у меня есть, выглядит так:

[
 {"contact" : 
           { information: {name: "abc", address:"asdfa"},
           type: "phone"
           value: "123212123"

}
]

ожидаемый выходной объект выглядит так:

[
  {
    name: 'contact',
    children: [

 {name: "infmormation",
       children: [
           {name: "address",
       children: [
          {name: 'absdsdc'},
    
        ]},
          {name: "name",
       children: [
          {name: 'adasdf'},
    
        ]},
    
        ]},
 
      {name: "type",
       children: [
          {name: 'abc'},
    
        ]},
          {name: "type",
       children: [
          {name: 'Broccoli'},
    
        ]},
      
    ]
  }

]

как Я могу создать древовидный объект для моего входного объекта с помощью функции динамического c, как создать рекурсивный метод, который может создавать метод вывода dynmia c. Мне нужна ваша помощь. любое решение?

1 Ответ

0 голосов
/ 03 августа 2020

В html

<mat-tree [dataSource]="dataSource" [treeControl]="treeControl" >
    <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle matTreeNodePadding>
      <span>{{node.name}}</span>
      [...]
    </mat-tree-node>
</mat-tree>

В Ц

//Variables tree
treeControl: FlatTreeControl<FileFlatNode>;
treeFlattener: MatTreeFlattener<YourObject, FileFlatNode>;
dataSource: MatTreeFlatDataSource<YourObject, FileFlatNode>;
transformer = (node: YourObject, level: number) => {
    return new FileFlatNode(node.name,node.expandable,node.level,node.childrens);
}

// Functions tree
private _getLevel = (node: FileFlatNode) => node.level;
private _isExpandable = (node: FileFlatNode) => node.expandable;
private _getChildren = (node: YourObject): Observable<YourObject[]> => 
observableOf(node.childrens);

//Inherit class represent tree node
export class FileFlatNode {
  constructor(public name: string,
              public expandable: boolean,
              public level: number,
              public childrens: YourObject[]) {
     //Here you can do the mapping between your object and the tree node
  }
}

// In constructor of main class
this.treeFlattener = new MatTreeFlattener(this.transformer, this._getLevel,
this._isExpandable, this._getChildren);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...