使用get_and_update Elixir修改并返回地图列表

时间:2018-02-12 11:22:55

标签: elixir

所以我的目标是获取地图列表,例如:

[%{"ts" => 1365111111, "url" => "http://example1.com"}, %{"ts" => 1365111115, "url" => "http://example2.com"}]

使用DateTime module转换ts密钥的unix时间戳值 并返回一个新的地图集合:

[%{"ts" => #DateTime<2013-04-04 21:31:51Z>, "url" => "http://example1.com"},%{"ts" => #DateTime<2013-04-04 21:31:51Z>, "url" => "http://example2.com"}]

所以我尝试使用get_and_update/3这样:

merge_maps =  [%{"ts" => 1365111111, "url" => "http://example1.com"}, %{"ts" => 1365111115, "url" => "http://example2.com"}]

new_maps = Enum.map(merge_maps, fn elem ->
  Map.get_and_update!(elem, "ts", fn curr_value ->
    {curr_value, curr_value |> DateTime.from_unix!} end)
end)

如何在new_maps中返回修改后的地图列表,而不是当前返回的元组列表:

[       
  {1365111111,
   %{"ts" => #DateTime<2013-04-04 21:31:51Z>, "url" => "http://mandrill.com"}},
  {1365111111, %{"ts" => #DateTime<2013-04-04 21:31:51Z>}}
]

1 个答案:

答案 0 :(得分:5)

您需要的是Map.update!/3,而不是Map.get_and_update/3

new_maps = Enum.map(merge_maps, fn elem ->
  Map.update!(elem, "ts", fn curr_value -> curr_value |> DateTime.from_unix! end)
end)

或只是

new_maps = Enum.map(merge_maps, fn elem ->
  Map.update!(elem, "ts", &DateTime.from_unix!/1)
end)