VueJS display grouped array of objects
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 name
s.
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>
Terry
Frontend engineer, PhD in Molecular Biology, amateur bioinformatician. Also likes to dabble in photography. Sometimes clumsy. In that order.
Updated on June 14, 2022Comments
-
Terry almost 2 years
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?
-
Terry over 6 yearsVueJS does not have helper methods like that for grouping of data: it is not designed to do that. It simply provides a framework for MVVC data binding. Can you share an example of the JSON response you get?
-
Lazar Ljubenović over 6 yearsI am not sure what is the actual question here.
-
Admin over 6 years@Terry sure, this is the exact response restcountries.eu/rest/v2/all
-
Lazar Ljubenović over 6 yearsWhat does your current code output?
-
-
Admin over 6 yearsAfter thinking about it a bit, I came to the same conclusion. Thanks for help!
-
Guillaume over 5 yearsHow can you
groupBy
with 2 keys ?