There are similar questions such as Build a Tree of Structs but I haven’t found any that would deal with exactly the same issue that I need to solve.
Let’s say we have an (unsorted) set of data that we load from DB
[
%{id: 2, name: "Child 2", parent_id: nil},
%{id: 1 ,name: "Child 1", parent_id: nil},
%{id: 3, name: "GrandChild 1", parent_id: 1},
%{id: 5, name: "Child 3", parent_id: nil},
%{id: 6, name: "GrandGrandChild 1", parent_id: 3},
]
Desired result
[
%{
id: 2,
name: "Child 2",
children: [],
},
%{
id: 1,
name: "Child 1",
children: [
%{
id: 3,
name: "GrandChild 1",
children: [
%{
id: 6,
name: "GrandGrandChild 1",
children: []
},
]
},
],
},
%{
id: 5,
name: "Child 3",
children: [],
},
]
There can be N levels, not just 3