2017-11-30 7 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 구성 요소를 사용하고 있고 루트 항목 2 개를 허용하지 않습니다 ... thats is is – Richie

+0

@ 제프 귀하의 제안은 완벽 해 보입니다. 나 한테 해봐 줄래? – Richie