Having an issue similar to https://elixirforum.com/t/whats-the-best-way-to-access-and-retrieve-data-from-deeply-nested-maps-and-lists/613/4.
I have a data structure with a nested map I’d like to accumulate into a list. The problem is I don’t know how to recursively get the maps of nested elements.
Here is a contrived version. I’m trying to get a list of all the c and nested c values. Is there a way to do this?
test "Recursive Maps" do
#I just want all the c's in a list
rMap = %{:a => 1, :b => 2, :c => %{ :a => 111, :b => 2222,
:c => %{ :a => 212, :b => 323,
:c => %{:a => 45, :b => 524,
:c => %{}}}}}
rMap2 = %{:a => 3, :b => 4,
:c => %{ :a => 5, :b => 6,
:c => %{ :a => 7, :b => 8,
:c => %{:a => 9, :b => 10,
:c => %{a: 11, b: 12, c: 13}}}}}
rMaps = [rMap,rMap2]
IO.puts "rMaps List of Justcs"
IO.inspect rMaps
justCs = justc rMaps
IO.inspect justCs
justCs = justc3 rMaps
IO.inspect justCs
end
# Loop through list
def justc3(rMaps) do
Enum.reduce_while(rMaps, [], fn rMap, acc ->
if Map.has_key?(rMap,:c) == false do
{:halt, acc}
else
c = Map.get(rMap,:c)
{:cont, [c] ++ acc}
end
end)
end
def justc(rMaps) do
justCs = for rMap <- rMaps do
c = Map.get(rMap,:c)
# IO.inspect Enum.count(c)
if Enum.count(c) == 0 do
[]
else
Map.get(rMap,:c)
end
end
end