我正在从API中获取一个国家/地区列表,我希望按子区域(大陆)将它们分组显示。就像这样:

API给了我一个响应,它是一个对象(国家)数组,对于每个对象,都有一个名为“子区域”的键-我想按该键进行分组。我使用lodash进行分组,但可能有一种我不熟悉的Vue方法。我的JS代码:
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();
},
},
});和HTML:
<li v-for="country in countries">
{{ country.name }} (+{{ country.callingCodes[0] }})
</li>我如何才能实现图片中的内容?
发布于 2017-08-28 00:52:55
您已经通过以下代码使用lodash正确地将国家按其子区域进行了分组。
_.groupBy(countryList, "subregion")这为您提供了一个对象,其键是子区域的名称,值是具有此子区域的对象的数组。
因此,您的错误在于期望countries中的值包含name。相反,它包含一个带有names的对象数组。
为此,您需要两个for循环。
这里是一个普通的实现。这也是a bin。
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])
})
})
})使用Vue,您将拥有如下内容(未经过测试,但根据上面的代码可以非常容易地推断出来)。
<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
复制相似问题