I'm trying to make build nested hierarchy from the defined input data, and I`m faced some problem with the deep level hierarchy. So, as an input there is array of objects, looks like this:
[
{
id: 1,
parentId: 1,
},
{
id: 2,
parentId: 1,
},
{
id: 3,
parentId: 2,
},
{
id: 4,
parentId: 3,
},
...
]
Every element has his own id and parentId. As outcome, I want to have the structure, grouped by the parent id's, smth like this:
{
id: 1,
sub: [
{
id: 2,
parentId: 1,
sub: [
{
id: 3,
parenId: 2,
},
....
],
},
],
}
So, the problem is how to build algorithm that will recursively goes through this input data, and build such structured outcome? When I know the level of hierarchy, I could build algorithm with defined level of nested loops, but the problem is with unknown number of deeper.