I need your help or advice on how to create the tree element for the project with data from the database. I have the same table for transformation into a tree.

On the picture the fields CounterpartyGroupParentId where 0 is entered points and it is the root of the tree. Then from the next field by filter method, I take the CounterpartyGroupName and the CounterpartyGroupId as can see it is the 10,11. When we have Id 10,11 by filter I take next CounterpartyGroupParentId where 10,11 also exist. The next step is finding elements in CounterpartyGroupId where 13,15 are accordingly with item4,item6. It is the second layer of the tree. For the third layer, I am looking for the CounterpartyGroupParentId with the same id 13 and 15 and receive the item5,item8 for Id 13, and Item3 for 15. The next structure must be finished tree in DOM:
.
I tried to realize it in the projects.
rootarray: any[] = [];
treview_array(arr): CounterpartyGroupTree[] {
var secondroot = [],
roots = [];
roots = arr.filter((x) => x.counterpartyGroupParentId == 0);
roots.forEach((val) => {
this.rootarray.push({
name: val["counterpartyGroupName"],
id: val["counterpartyGroupId"],
children: [],
});
}, this);
for (let i = 0; i < this.rootarray.length; i++) {
secondroot.push(
arr.filter(
(x) => x.counterpartyGroupParentId == this.rootarray[i]["id"]
)
);
}
let filteredarray = [...secondroot[0], ...secondroot[1]];
filteredarray.forEach((val, index) => {
this.rootarray[index]["children"].push({
name: val["counterpartyGroupName"],
id: val["counterpartyGroupId"],
children: [],
});
}, this);
var thirdroot = [];
for (let k = 0; k < this.rootarray.length; k++) {
for (let l = 0; l < this.rootarray[k]["children"].length; l++) {
if (this.rootarray[l]["children"] != 0) {
thirdroot.push(
arr.filter(
(x) =>
x.counterpartyGroupParentId ==
this.rootarray[l]["children"][l]["id"]
)
);
}
}
}
var filteredroot = [...thirdroot[0], ...thirdroot[1]];
filteredroot.forEach((val, index) => {
if (
val["CounterpartyGroupParentId"] ==
filteredarray["counterpartyGroupId"]
) {
this.rootarray[index]["children"][0]["children"].push({
name: val["counterpartyGroupName"],
id: val["counterpartyGroupId"],
children: [],
});
} else {
this.rootarray[index]["children"][0]["children"].push({
name: val["counterpartyGroupName"],
id: val["counterpartyGroupId"],
children: [],
});
}
});
console.log(this.rootarray);
return this.rootarray;
}
And interface
export interface CounterpartyGroupTree{
name:string;
id: number;
children?:CounterpartyGroupTree[];
}
On the third layer, I have the mash and difficulty to insert chosen data in the tree.