arrays - 按值分组 json 数组
问题描述
我对 Vue 比较陌生,正在尝试按国家/地区组织 API 响应,然后按国家/地区组织。以下是来自 API 的示例响应:
[
{
"id": 1,
"title": {
"rendered": "Test 1"
},
"acf": {
"address_property": {
"city": "Lenox",
"state": "Massachusetts",
"country": "United States",
}
}
},
{
"id": 2,
"title": {
"rendered": "Test 2"
},
"acf": {
"address_property": {
"city": "Branson",
"state": "Missouri",
"country": "United States",
}
}
},
{
"id": 3,
"title": {
"rendered": "Test 3"
},
"acf": {
"address_property": {
"city": "Branson",
"state": "Missouri",
"country": "United States",
}
}
},
{
"id": 4,
"title": {
"rendered": "Test 4"
},
"acf": {
"address_property": {
"city": "Tallinn",
"country": "Estonia",
}
}
}
]
我在页面上成功打印了代码,但是,我没有成功组织这些信息。以下是理想的输出:
美国
马萨诸塞州
- 测试 1
密苏里州
- 测试 2
- 测试 3
国际的
爱沙尼亚
- 测试 4
我目前的代码是:
data: function() {
return {
properties: []
};
},
methods: {
loadDestinations: function() {
axios
.get("//localhost:81/wp-json/wp/v2/properties?_embed")
.then(response => {
sessionStorage.setItem("properties", JSON.stringify(response.data));
this.properties= response.data;
return response.data;
})
.catch(error => {
console.error(error); // for debugging maybe
});
}
},
mounted() {
if (sessionStorage.getItem("properties")) {
this.properties= JSON.parse(sessionStorage.getItem("properties"));
} else {
this.loadDestinations();
}
}
解决方案
你可以用reduce尝试这样的事情:
let data = [
{
"id": 1,
"title": {
"rendered": "Test 1"
},
"acf": {
"address_property": {
"city": "Lenox",
"state": "Massachusetts",
"country": "United States",
}
}
},
{
"id": 2,
"title": {
"rendered": "Test 2"
},
"acf": {
"address_property": {
"city": "Branson",
"state": "Missouri",
"country": "United States",
}
}
},
{
"id": 3,
"title": {
"rendered": "Test 3"
},
"acf": {
"address_property": {
"city": "Branson",
"state": "Missouri",
"country": "United States",
}
}
},
{
"id": 4,
"title": {
"rendered": "Test 4"
},
"acf": {
"address_property": {
"city": "Tallinn",
"country": "Estonia",
}
}
}
]
let grouped = data.reduce((acc, obj) => {
let outerKey = obj.acf.address_property.state === undefined ? 'International' : obj.acf.address_property.country
let innerKey = outerKey === 'International' ? obj.acf.address_property.country : obj.acf.address_property.state
if (!acc[outerKey]) { acc[outerKey] = {} }
if (!acc[outerKey][innerKey]) { acc[outerKey][innerKey] = [] }
acc[outerKey][innerKey].push(obj.title.rendered)
return acc
}, {})
console.log(grouped)
推荐阅读
- angular - 不获取反应形式的输入值(Angular5)
- c++ - 为什么添加更多变量和/或指令后程序大小保持不变?
- reactjs - 从 react PWA 中读取 BLE 信标
- pytorch - 如何在 pytorch 中将张量插入另一个张量
- php - 在 Woocommerce 中更改“我的帐户”页面上的标题
- angularjs - 尝试在 AngularJS 的控制器中访问我的服务中的变量
- python - 如何添加 QProcess PATH 环境变量的路径?(Python 3.7 上的 PyQt5)
- javascript - 浏览器 javascript 输出不显示类名(与 Node 不同)
- angular - angular - Angular 6 如何编辑日期格式?
- lucene - 在 Lucene 文档中获取术语位置的正确方法是什么?