我有一个 API,它以以下格式返回数据:[ { "id": 12, "acf": { "address": { "city": "Bandar Penawar", "state": "Johor", "country": "Malaysia", } }, { "id": 16, "acf": { "address": { "city": "Some City", "state": "Arizona", "country": "United States", } }]现在,我正在获取具有以下计算代码的国家和州列表:computed: { countries() { const countries = new Set(); this.$store.state.posts.forEach((post) => countries.add(post.acf.address.country) ); return Array.from(countries); }, states() { const states = new Set(); this.$store.state.posts.forEach((post) => states.add(post.acf.address.state) ); return Array.from(states); }, },这将返回两个单独的数组,countries并且states,如何按国家/地区以及该国家/地区内的州组织数组?
1 回答
慕哥6287543
TA贡献1831条经验 获得超10个赞
您可以使用一个字典,其键是国家/地区名称,值是州数组:
computed: {
dictionary() {
const dictionary = {};
this.$store.state.posts.forEach(post => {
const c = post.acf.address.country;
const s = post.acf.address.state;
dictionary[c] = dictionary[c] || [];
!dictionary[c].includes(s) && dictionary[c].push(s);
});
return dictionary;
}
}
处理重复:如果&&/push语句看起来很奇怪,那么它就像一个简短的if语句,测试状态是否已经在列表中,如果不在则只到达推送语句
添加回答
举报
0/150
提交
取消