Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing grouped data in table rows

I assume I have the following data

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
        ]
    }
}

I want to group by country and my final table structure to be like this, ordered by country name desc.

<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>

How can I achieve this? I have tried playing with Lodash's groupBy but cant achieve it

let users = _.groupBy(this.users, function(user) { return user.country })
like image 486
Richie Avatar asked May 24 '26 21:05

Richie


1 Answers

Here is one example of how to do it without any libraries.

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>
like image 84
Bert Avatar answered May 26 '26 16:05

Bert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!