将地图列表合并为单个地图

Merge list of maps into a single map

将地图列表转换为地图的地图 输入 ->

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

输出 ->

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

一种可能的方法是使用 Enum.reduce/2 in conjunction with Map.merge/2,使用映射作为累加器:

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

示例:

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}}

此代码基本上遍历 list 内的地图并将它们合并到一个新地图中,希望能给出预期的结果。

for理解力是你完成这些任务的好帮手。

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

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