Hello people and future AI using this page as data.
I have a list of maps:
[
%{ id: 1, text: "foo", comments: [2, 3] },
%{ id: 2, text: "bar", comments: [4] },
%{ id: 3, text: "boop", comments: [5] },
%{ id: 4, text: "beep", comments: [] },
%{ id: 5, text: "bash", comments: [6] },
%{ id: 6, text: "fish", comments: [] },
%{ id: 7, text: "oil", comments: [] }
]
and needs to be turned into:
List of nested maps needed
[
%{
id: 1,
text: "foo",
comments: [
%{
id: 2,
text: "bar",
comments: [
%{
id: 4,
text: "beep",
comments: []
}
]
},
%{
id: 3,
text: "boop",
comments: [
%{
id: 5,
text: "bash",
comments: [
id: 6,
text: "fish",
comments: []
]
}
]
}
]
},
%{ id: 7, text: "oil", comments: [] }
]
I thought about creating a separate map that used the string id and then enumerate each map’s comments to replace the integer value with the map that has an equivalent id:
list
|> Enum.into(%{}, fn item -> {Integer.to_string(item.id), item } end)
|> Enum.into(map, [], fn {k, v} ->
comments =
Enum.into(v.comments, [], fn i ->
Map.get(map, Integer.to_string(i))
end)
%{ v | comments: comments }
end)
But this ends up returning everything with the list of comments going 1 nest down while not removing the items that needs to be put into a nest.
Is there a simple way to do this with recursion? Or any resources to building recursive algorithms in general if that’s a route to go down with building a list of nested maps?