1365111111, "url" => "http://example1.com"}, %{"ts" => 1365111115, "-6ren">
gpt4 book ai didi

elixir - 使用 get_and_update Elixir 修改并返回 map 列表

转载 作者:行者123 更新时间:2023-12-04 16:06:19 29 4
gpt4 key购买 nike

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

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

使用 DateTime module 转换 ts 键的 unix 时间戳值并返回一个新的 map 集合:

[%{"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 中返回修改后的 map 列表,而不是当前返回的元组列表:

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

最佳答案

您需要的是 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)

关于elixir - 使用 get_and_update Elixir 修改并返回 map 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48745312/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com