My JSON object consists of several nestings:
{
"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
}
In this JSON I want to sort the data in the seperate groups in "0" and "yearlyResults" in ascending order....
My Code:
/**
* 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'));
...
}
}
}
My solution approach works, however I don't find it efficient enough! With two groups it is still ok to sort so, but if I have 20 or 30 I can no longer perform so. Can I sort the JSON groups by iterating somehow? Can you help me please?