I have a JSON object with multiple nested levels:
{
"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": {
// Structured similarly to firstGroup
}
},
"success": true
}
My goal is to sort the data within the "0" and "yearlyResults" groups in ascending order within this JSON....
Here's the code I'm using:
/**
* Function for sorting data in ascending order
* @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;
};
}
/**
* Display sorted data using this function
*/
private getSortedData() {
this.myService.getData().subscribe();
(resp: any) => {
const data = resp.success ? resp.myJson : null;
// Sorting for firstGroup
const firstData = data['firstGroup'];
const currentFirstData = firstData['0'];
const currentFirstYearly = firstData.yearlyResults['0'];
// Sorting for secondGroup
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'));
...
}
}
}
While my solution works, it may not be efficient enough! Sorting two groups is manageable, but with 20 or 30 groups, it becomes more challenging. Is there a way to iterate through and sort the JSON groups? Any assistance would be greatly appreciated!