I have this list in my front-end typescript file:
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 would like to get a nested typed tree out of it, something similar to this but in a typed format:
So I am using this function to group the list to what I want:
groupBy() {
const result = this.poMonths.reduce((state, current) => {
const { companyName, year, month } = current;
const company = state[companyName] || (state[companyName] = {});
const yearObj = company[year] || (company[year] = {});
const monthArr = yearObj[month] || (yearObj[month] = []);
monthArr.push(current);
return state;
}, {});
return result;
}
However, the returned value is not typed, it is just a JSON object. How can I make it typed utilizing these types for instance?:
export class ItemNode {
children: ItemNode[];
item: string;
}
/** leaf item node with database id information. each leaf will be a single leaf containing an id from the database */
export class LeafItemNode {
id?: number;
companyId: number;
companyName: string;
flActive: boolean;
purchaseMonth: Date;
purchaseMonthString: string;
year: number;
month: number;
}
Basically, the tree should consist of ItemNodes all the way down to the leaves which would be LeafItemNode (containing the IDs)
