VueJS display grouped array of objects

青春壹個敷衍的年華 提交于 2020-01-03 02:29:05

问题


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

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?


回答1:


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>


来源:https://stackoverflow.com/questions/45906741/vuejs-display-grouped-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!