How can I sort a complex JSON object efficiently?
You can you Object.entries
in order to iterate thought all key-value
pairs and then use Array.prototype.reduce
for composing the new object. Like so:
const data = JSON.parse('{ "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 } ] } } }, "success": true }');const object = data.myJson;const sortSubGroupByProperty = (subGroup, property) => { return subGroup.sort((a, b) => { if (a[property] > b[property]) { return 1; } else if (a[property] < b[property]) { return -1; } return 0; });}const result = Object.entries(object).reduce((result, entry) => { const [groupName, group] = entry; result[groupName] = { ...group, 0: sortSubGroupByProperty(group[0], 'nr'), yearlyResults: { ...group.yearlyResults, 0: sortSubGroupByProperty(group.yearlyResults[0], 'nr') } }; return result;}, {});console.log(result);
Here in the snippet everything runs without errors.I have the problem in the IDE. I have implemented the code like this:
this.kpisService.getAllKpisMonthData(yearString).subscribe( (resp: any) => { const data = resp.success ? resp.kpi : null; // console.table(data); if (null !== data && data) { const sortSubGroupByProperty = (subGroup, property) => { return subGroup.sort((a, b) => { if (a[property] > b[property]) { return 1; } else if (a[property] < b[property]) { return -1; } return 0; }); }; const result = Object.entries(data).reduce((result, entry) => { const [groupName, group] = entry; result[groupName] = { ...group, // Here is the problem 0: sortSubGroupByProperty(group[0], 'nr'), yearlyResults: { ...group.yearlyResults, 0: sortSubGroupByProperty(group.yearlyResults[0], 'nr') } }; return result; }, {}); console.log(result);