如何动态地将子项附加到对象

时间:2018-03-27 07:00:25

标签: javascript angular

假设我有一个如下所示的对象:

var ob = [
    {name: "root",id: 1},
    {name: "root2",id: 2}
];

我想动态地将子对象附加到它上面。例如: 假设如果我点击id 1,则应将children对象附加到ob对象。

    var ob = [
        {name: "root",id: 1, children: [
                 {name: 'sub1', id:'5'},
                 {name: 'sub2', id:'6'},
               ]
        },
        {name: "root2",id: 2}
    ];

现在,如果我再次点击id 6,则应将子项添加到id 6.

var ob = [
        {name: "root",id: 1, children: [
                 {name: 'sub1', id:'5'},
                 {name: 'sub2', id:'6', children: [
                                 {name: 'subsub1', id:'8'},
                                 {name: 'subsub2', id:'9'},
                                 ]
                 },
               ]
        },
        {name: "root2",id: 2}
    ];

我正在尝试为它编写递归函数但没有成功。点击任何一个术语,我只参考点击的术语。我不知道父母的用语。

修改 以下是我的代码:

<div *ngFor = "let term of terms">
  <div class="row tr">
        <a (click) = "showTerms($event)">{{term.id}}</a>
  </div>
  <div class="col-xs-6">{{term.desc}}</div>

  <app-icd-codes *ngIf = "term.children" [terms] = "term.children"></app-icd-codes>
 </div>

点击标签我正在添加儿童。所以我需要创建一个动态对象并更新该对象,如上所示。

1 个答案:

答案 0 :(得分:1)

最简单的方法是将&#34; terms&#34;的索引作为参数传递。放两个按钮,一个用于AddTerms,另一个用于hideTerms / showTerms。

<div *ngFor = "let term of terms;let i=index">
 <!--see the way to get the index of the array -->
  <div class="row tr">
    {{term.id}}
    <!--you make a link, I use a button-->
    <!--the button "add" is visible when there're NOT "children"-->
    <button *ngIf="!term.terms" (click)="addTerms(i)">Add</button>  
    <!--the button to Show/hide is visible when there ARE "children"-->
    <button *ngIf="term.terms" (click)="term.show=!term.show">
      <span *ngIf="term.show">^</span>
      <span *ngIf="!term.show">v</span>
    </button>
  </div>
  <ng-container *ngIf ="term.terms && term.show">
    <app-icd-codes [terms]="term.terms"></app-icd-codes>
  </ng-container>
</div>

然后你必须把你的函数addTerms。一个简单的函数可以像

//see that you received the "index" of children
addTerms(index: number) {
    this.terms[index].show = true; //<--to show the children
    this.terms[index].terms = [{ id: 3 }, { id: 4 }]; //a "easy" way to add
  }

好的,这个功能真的必须像

addTerms(index: number) {
    let id=this.terms[index].id; //we get the "id"
    //call a httpClient and subscribe
    this.httpClient.get("url/"+id).subscribe(res=>
          //in the subscription
          {
             this.terms[index].show = true; //<--to show the children
             this.terms[index].terms = res
          })
}

注意:可能导致&#34;奇怪&#34;向对象添加新属性(在本例中为&#34; children&#34;和&#34; show&#34;)。如果我们感觉更加舒适,我们可以在创建具有空值的对象时添加属性