Search code examples
javascriptvue.jsfrontendlodash

VueJS display grouped array of objects


I'm fetching a list of countries from the API and I want to display them in groups by subregion (continent). Like that:

enter image description here

API gives me a response which is an array of objects (countries) and for each object there is a key called 'subregion' - I want to group by that key. I use lodash for grouping, but maybe there is a Vue method I'm not familiar with. My JS code:

var app = new Vue({
  el: '#app',

  data: {
    countries: null,
  },

  created: function () {
    this.fetchData();
  },

  methods: {
    fetchData: function() {
      var xhr = new XMLHttpRequest();
      var self = this;
      xhr.open('GET', apiURL);
      xhr.onload = function() {
        var countryList = JSON.parse(xhr.responseText);
        self.countries = _.groupBy(countryList, "subregion");
      };
      xhr.send();
    },
  },
});

And HTML:

<li v-for="country in countries">
        {{ country.name }} (+{{ country.callingCodes[0] }})
</li>

How can I achieve what's in the picture?


Solution

  • You've correctly grouped countries by their subregion using lodash with the following code.

    _.groupBy(countryList, "subregion")
    

    This has given you an object whose keys are names of subregions, and the values are arrays of objects with such subregion.

    So your mistake is that you expect a value in countries to contain name. Instead, it contains an array of objects with names.

    You need two for-loops for this.

    Here's a vanilla implementation. Here's a bin, too.

    fetch('https://restcountries.eu/rest/v2/all')
      .then(r => r.json())
      .then(data => {
        const grouped = _.groupBy(data, 'subregion')
        const listOfSubregions = Object.keys(grouped)
    
        listOfSubregions.forEach(key => {
          console.log(' =========== ' + key + ' =========== ')
          const countriesInThisSubregion = grouped[key]
          countriesInThisSubregion.forEach(country => {
            console.log(country.name + ' ' + country.callingCodes[0])
          })
        })
      })
    

    With Vue, you'd have something like the following (not tested, but should be super-easy to deduce based on the above code).

    <li v-for="subregion in subregions">
      <ul>
        <li v-for="country of subregion">
            {{ country.name }} ({{ country.callingCodes[0] }})
        </li>
      </ul>
    </li>