I'm facing a challenge with my script. I have an Array of FlatObj and some rules, and I need to create a converter function that transforms them into TreeObj.
The Rules are:
- If an object has a higher depth, it should be a child of an object with a lower adjacent depth
- "ROOT" will be the root node of the TreeObj
interface FlatObj {
id: String;
depth: number;
}
interface TreeObj {
id: String;
children?: TreeObj[];
}
const data: FlatObj[] = [
{
id: "ROOT",
depth: 0
},
{
id: "G1",
depth: 1
},
{
id: "G2",
depth: 1
},
{
id: "G2-1",
depth: 2
},
{
id: "G2-2",
depth: 2
},
{
id: "G2-2-1",
depth: 3
},
{
id: "G3",
depth: 1
}
];
const converter = (data: FlatObj[]): TreeObj => {
// logic for converting FlatObj to TreeObj ...
}
The expected result should resemble this structure
{
id: "ROOT",
children: [
{ id: "G1" },
{
id: "G2",
children: [
{ id: "G2-1" },
{
id: "G2-2",
children: [ { id: "G2-2-1" } ]
}
]
},
{ id: "G3" },
]
}
I'm open to any suggestions or ideas on how to tackle this problem effectively.