I have a parts list in the following structure:
level | description
0 | sfg
1 | sdf
2 | asdisg
3 | sidjhf
4 | wefdsj
4 | asdfg
4 | sgfd
4 | sdg
3 | sfg
3 | fdg
4 | sdfg
4 | sdsfd
4 | sdf
4 | sdf
2 | adf
3 | sdfg
4 | sdg
4 | sdf
4 | sdf
4 | sdf
1 | shfg
2 | ijsd
3 | ijsd
4 | sdf
4 | sdf
What I need is to convert this part list into a hierarchy folder structure like this (prefered in nested JSON):

I want to use the following structure in TypeScript:
export interface Foo {
level: number;
description: string;
children?: Foo[];
}
What I need is a nested JSON object or something like a nested array in which the array contains children with another array.
Unfortunately I have only pseudocode to show (I know, this will never work):
recursiveWalker(List, lastLevel, parent) {
for (let i = 0; i < List.length; ++i) {
const node = {
description: List.description,
level: List.level
};
if (List.level === lastLevel + 1) {
node.children = this.recursiveWalker(List, lastLevel + 2, node);
}
}
return node;
}
My question is now: Is there a simple solution to create such nested data? Do I have to use recursive functions, or are there any algorithms which I can implement?
The goal is to create a material tree in Angular (https://material.angular.io/components/tree/overview) with this data.
I really appreciate any kind of help!
UPDATE: The following structure will be needed:
const bar: Foo = {
description: 'this is level 0 (root)',
level: 0,
children: [{
description: 'this is level 1',
level: 1,
children: [
{
description: 'this is level 2',
level: 2
},
{
description: 'this is level 2',
level: 2
},
{
description: 'this is level 2',
level: 2,
children: [
{
description: 'this is level 3',
level: 3
},
{
description: 'this is level 3',
level: 3
},
{
description: 'this is level 3',
level: 3,
children: [] /* AND SO ON .... */
}
]
}
]
}]
};
});