2017-11-30 6 views
0

リスト私は国の名前の降順で注文した本、のようになり、国と私の最後のテーブル構造によってグループ化したい私は、次のデータを持っているテーブルの行でグループ化されたデータに

data() { 
    return { 
     users: [ 
      {country: 'USA', name: 'Taylor'}, 
      {country: 'UK', name: 'Tony'}, 
      {country: 'USA', name: 'Mary'}, 
      {country: 'JAPAN', name: 'Jane'}, 
      {country: 'JAPAN', name: 'Moses'}, 
      // More users from different countries in the world 
     ] 
    } 
} 

を前提としています。

<table> 
    <tr> 
     <th>Country</th> 
     <th>User</th> 
    </tr> 
    <tr> 
     <td colspan="2">USA</td> 
    </tr> 
    <tr> 
     <td></td> 
     <td>Taylor</td> 
    </tr> 
    <tr> 
     <td></td> 
     <td>Mary</td> 
    </tr> 
    <tr> 
     <td colspan="2">UK</td> 
    </tr> 
    <tr> 
     <td></td> 
     <td>Tony</td> 
    </tr> 
    <tr> 
     <td colspan="2">JAPAN</td> 
    </tr> 
    <tr> 
     <td></td> 
     <td>Jane</td> 
    </tr> 
    <tr> 
     <td></td> 
     <td>Moses</td> 
    </tr> 


</table> 

どうすればこの問題を解決できますか?私はLodashのGROUPBYで遊んで試してみましたが、ここで

let users = _.groupBy(this.users, function(user) { return user.country }) 

答えて

2

は、任意のライブラリなしでそれを行う方法の一例である、それを達成傾けます。

console.clear() 
 

 
new Vue({ 
 
    el: "#app", 
 
    data:{ 
 
    users: [ 
 
     {country: 'USA', name: 'Taylor'}, 
 
     {country: 'UK', name: 'Tony'}, 
 
     {country: 'USA', name: 'Mary'}, 
 
     {country: 'JAPAN', name: 'Jane'}, 
 
     {country: 'JAPAN', name: 'Moses'}, 
 
     // More users from different countries in the world 
 
    ] 
 
    }, 
 
    computed:{ 
 
    byCountry(){ 
 
     return this.users.reduce((acc, user) => { 
 
     (acc[user.country] = acc[user.country] || []).push(user.name) 
 
     return acc 
 
     }, {}) 
 
    } 
 
    } 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script> 
 
<div id="app"> 
 
    <table> 
 
    <tr> 
 
     <th>Country</th> 
 
     <th>User</th> 
 
    </tr> 
 
    <template v-for="people, country in byCountry"> 
 
     <tr> 
 
     <td colspan="2">{{country}}</td> 
 
     </tr> 
 
     <tr v-for="person in people"> 
 
     <td></td> 
 
     <td>{{person}}</td> 
 
     </tr> 
 
    </template>  
 
    </table> 
 
</div>

+0

テンプレートタグは、すべてのブラウザでは動作しません。単一の「」を使用するには、すべてをフラットな配列にする必要があります。それ以外の場合は、IEは正しく表示されません。 – Jeff

+0

@Bert私はVueコンポーネントを使用しています。 – Richie

+0

@ジェフあなたの提案は完璧に見えます。私のためにそれを試してもらえますか? – Richie

関連する問題