按值分组 json 数组
Posted
技术标签:
【中文标题】按值分组 json 数组【英文标题】:Group json array by value 【发布时间】:2020-11-26 00:28:47 【问题描述】:我对 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();
【问题讨论】:
【参考方案1】:你可以用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)
【讨论】:
太棒了,完美运行!谢谢你教会了我一些新东西。【参考方案2】:您可以使用这样的方法在显示数据之前重新组织数据:
function prepareData(data)
var countries = ;
data.forEach(function(entry)
if (!(entry.acf.address_property.country in countries))
countries[entry.acf.address_property.country] = ;
if (!(entry.acf.address_property.city in countries[entry.acf.address_property.country]))
countries[entry.acf.address_property.country][entry.acf.address_property.city] = [entry];
else
countries[entry.acf.address_property.country][entry.acf.address_property.city].push(entry);
)
return countries;
this.properties = prepareData(response.data);
【讨论】:
以上是关于按值分组 json 数组的主要内容,如果未能解决你的问题,请参考以下文章
将javascript数组中的重复值分组在一起,然后按值名称升序对这些组进行排序