【发布时间】:2021-09-11 10:27:06
【问题描述】:
我的 JSON 对象由几个嵌套组成:
{
"myJson": {
"firstGroup": {
"0": [
{
"month": 1.0,
"amount": 1.7791170955479318,
"name": "dummy1",
"nr": 3
},
{
"month": 2.0,
"amount": 324.0,
"name": "dummy2",
"nr": 1
},
{
"month": 3.0,
"amount": 32323.0,
"name": "dummy3",
"nr": 2
}
],
"yearlyResults": {
"0": [
{
"month": 1.0,
"amount": 100000,
"name": "dummy1",
"nr": 3
},
{
"month": 2.0,
"amount": 3000000,
"name": "dummy2",
"nr": 1
},
{
"month": 3.0,
"amount": 60000,
"name": "dummy3",
"nr": 2
}
]
}
},
"secondGroup": {
// Built the same way as firstGroup
}
},
"success": true
}
在这个 JSON 中,我想按升序对“0”和“yearlyResults”中单独组中的数据进行排序......
我的代码:
/**
* Function to sort data ascending
* @param property any
*/
sortByProperty(property) {
return (a, b) => {
if (a[property] > b[property]) {
return 1;
}
else if (a[property] < b[property]) {
return -1;
}
return 0;
};
}
/**
* Show sorted data in this function
*/
private getSortedData() {
this.myService.getData().subscribe();
(resp: any) => {
const data = resp.success ? resp.myJson : null;
// firstGroup for sort
const firstData = data['firstGroup'];
const currentFirstData = firstData['0'];
const currentFirstYearly = firstData.yearlyResults['0'];
// secondGroup for sort
const secondData = data['secondGroup'];
const currentSecondData = secondData['0'];
const currentSecondYearly = secondData.yearlyResults['0'];
if (null !== data && data) {
currentFirstData.sort(this.sortByProperty('nr'));
currentFirstYearly.sort(this.sortByProperty('nr'));
currentcurrentSecondData.sort(this.sortByProperty('nr'));
currentSecondYearly.sort(this.sortByProperty('nr'));
...
}
}
}
我的解决方案可行,但我觉得它不够高效!有两组仍然可以排序,但如果我有 20 或 30 组,我就不能再这样做了。我可以通过某种方式迭代对 JSON 组进行排序吗?你能帮帮我吗?
【问题讨论】:
-
您要对所有组进行排序吗?还是具体的?
-
我要对所有组进行排序
-
所有组的结构都相同。有“0”和“yearlyResults”。这些将按升序排列。你知道怎么做吗?
-
只能有“1”、“2”等还是“0”?
-
是的,也可能有 1,2,3。但我只在 0 中排序
标签: javascript json angular typescript