Merge list of maps into a single map

Viewed 206

convert a list of maps to a map of maps input ->

 [%{"cleiton" => %{"abril" => 346,...}}, %{"pedro" => %{...}}]

output ->

 %{"cleiton" => %{"abril" => 346,...} "pedro" => %{...}}
2 Answers

One possible way is to use the Enum.reduce/2 in conjunction with Map.merge/2, using a map as the accumulator:

Enum.reduce(list, &Map.merge/2)

Example:

iex(1)> list = [%{"cleiton" => %{"abril" => 346}}, %{"pedro" => %{"abril" => 123}}]
[%{"cleiton" => %{"abril" => 346}}, %{"pedro" => %{"abril" => 123}}]
iex(2)> Enum.reduce(list, &Map.merge/2)
%{"cleiton" => %{"abril" => 346}, "pedro" => %{"abril" => 123}}

This code basically iterates over the the maps inside list and merge them in a new map, hopefully giving the expected result.

for comprehension is your friend in such tasks.

for map <- [%{"cleiton" => %{"abril" => 346}},
            %{"pedro" => %{"may" => 42}}],
    {key, value} <- Map.to_list(map),
  into: %{},
  do: {key, value}

#⇒ %{"cleiton" => %{"abril" => 346}, "pedro" => %{"may" => 42}}
Related