In my front-end TypeScript file, there is a list called poMonths:
0: {id: 1, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-12-15T00:00:00", purchaseMonthString: "Dec-2019" , year: 2019, month: "December"}
1: {id: 2, companyName: "company5", companyId: 5, flActive: true, purchaseMonth: "2019-12-15T00:00:00", …}
2: {id: 3, companyName: "company13", companyId: 13, flActive: true, purchaseMonth: "2019-11-15T00:00:00", …}
3: {id: 4, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-11-15T00:00:00", …}
4: {id: 5, companyName: "company5", companyId: 5, flActive: true, purchaseMonth: "2019-10-15T00:00:00", …}
5: {id: 6, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2020-09-15T00:00:00", …}
6: {id: 7, companyName: "company7", companyId: 7, flActive: true, purchaseMonth: "2020-09-15T00:00:00", …}
I want to transform this list into a nested tree JSON structure grouped by companyName and year properties, similar to the image below but in JSON format:
https://i.sstatic.net/uPjPm.png
I found some code snippet that partially achieves this, but it needs some tweaking:
keys = [
'year',
'companyName'
];
groupBy() {
const drill = (o, key, ...keys) =>
key ? drill((o[key] = o[key] || {}), ...keys) : o;
const result = {};
for (const e of this.poMonths) {
const key = drill(
result,
e.companyName,
e.year,
e.month
);
}
return result;
}
How can I modify the code to make it work as intended?