2017-12-08 21 views
0

良い日には、私は、グループのタイトルで配列を表示する、私はWebサービスからの私の配列を取得しようとしてきたと私はグループのタイトルでアイテムを表示したいGROUPBY ngFor angular2

グループ1 項目1 項目2項目3

グループ2 項目1つの項目2 項目3

ここenter image description here

は長すぎるので、私はすべての配列データを貼り付けカント私の配列

   [ 
       { 
        "id": "1", 
        "title": "Item 1", 
        "groups": [ 
         { 
          "id": "2", 
          "title": "Communication" 
         } 
        ] 
       }, 
       { 
        "id": "2", 
        "title": "Item 2", 
        "groups": [ 
         { 
          "id": "2", 
          "title": "Communication" 
         } 
        ] 
       }, 
       { 
        "id": "3", 
        "title": "Item 1", 
        "groups": [ 
         { 
          "id": "1", 
          "title": "Creativie Art" 
         } 
        ] 
       }, 
       { 
        "id": "4", 
        "title": "Item 3", 
        "groups": [ 
         { 
          "id": "2", 
          "title": "Communication" 
         } 
        ] 
       }, 
       { 
        "id": "5", 
        "title": "Item 2", 
        "groups": [ 
         { 
          "id": "1", 
          "title": "Creativie Art" 
         } 
        ] 
       }, 
       { 
        "id": "6", 
        "title": "Item 3", 
        "groups": [ 
         { 
          "id": "1", 
          "title": "Creativie Art" 
         } 
        ] 
       } 
      ] 

であるが、これはここで配列構造

+0

私は理解しObject.assign({}、...値[ 'グループ'] );グループノードをオブジェクトに変換できますが、これが役立つかどうかわかりません。 – netx

+0

実際の配列を共有してください。 –

+0

私は実際の質問に書いた、それはサンプル配列と同じです。違いはありません – netx

答えて

5

でどのように我々はできるの一つの選択肢ですする:

app.component.ts

const groupsDict = this.arr.reduce((acc, cur) => { 
    cur.groups.forEach(({ id, title}) => { 
    acc[id] = acc[id] || { id, title }; 
    acc[id].items = acc[id].items || []; 
    acc[id].items.push({ id: cur.id, title: cur.title }); 
    }); 
    return acc; 
}, {}); 
this.groups = Object.keys(groupsDict).map(x => groupsDict[x]); 

app.component.html

<div class="grid"> 
    <div *ngFor="let group of groups" class="col"> 
    <h2>{{ group.title }}</h2> 
    <div *ngFor="let item of group.items"> 
     {{ item.title }} 
    </div> 
    </div> 
</div> 

Stackblitz Example

+0

が働いて、ありがとう! – netx