I am currently working on transforming a list into a tree structure suitable for a PrimeNG TreeTable.
[{pk:"1", corpID:"1234", date: "31/03/21", rela:"4325", price:"20.00"},
{pk:"2", corpID:"1234", date: "21/03/21", rela:"4425", price:"50.00"} ,
{pk:"3", corpID:"3456", date: "03/03/21", rela:"6327", price:"80.00"} ,
{pk:"4", corpID:"4567", date: "05/03/21", rela:"7328", price:"40.00"}]
My objective is to group the data first by corpId
, and then by rela
. The PrimeNG TreeTable requires a specific structure where data
represents the values displayed in each row, and children
contain the data within the expanded row. For reference, you can check out this link: https://www.primefaces.org/primeng/showcase/#/treetable
The desired structure should look like this:
{ data : [
{
data: {
corpID : "1234"
},
children: [
{
data:{
RELA: "4325"
},
children: [
{
data : { pk:"1",
corpID:"1234",
date: "31/03/21",
rela:"4325",
price:"20.00"},
}]
},
data:{
RELA: "4425"
},
children: [
{
{ pk:"2",
corpID:"2345",
date: "21/03/21",
rela:"4425",
price:"50.00"
}
]
...
I have attempted various methods such as grouping by and using a reduce function, but these approaches resulted in a condensed tree structure without the necessary inclusion of data
and children
attributes. Can someone advise on how to create the tree structure while retaining these attributes? Any assistance would be highly appreciated!
Below is an example of the function I tried, which effectively created the tree structure but lost some essential data attributes:
let result = this.data.reduce(this.totree, {});
totree(branches, node) {
if (!branches[node.corpId]) {
branches[node.corpId] = {};
}
branches[node.corpId][node.rela] = node;
branches[node.corpId][node.rela] = Object.assign(branches[node.corpId][node.rela]);
return branches;
}