我有以下 map 列表:
[
%{
code: "test",
expired_at: ~U[2020-10-27 17:49:47Z],
},
%{
code: "test",
expired_at: ~U[2021-07-30 13:54:11Z],
}
]
重命名 key 的最复杂方法是什么code
至 product_code
对于列表中的所有 map 实体?
最佳答案
可能不是“最复杂的方式”,但我认为使用模式匹配是一种不错的方式,使用带有子句的匿名函数来匹配您想要更改的内容,以及其他所有内容:
iex> l = [
...> %{
...> code: "test",
...> expired_at: ~U[2020-10-27 17:49:47Z],
...> },
...> %{
...> code: "test",
...> expired_at: ~U[2021-07-30 13:54:11Z],
...> }
...> ]
[
%{code: "test", expired_at: ~U[2020-10-27 17:49:47Z]},
%{code: "test", expired_at: ~U[2021-07-30 13:54:11Z]}
]
iex> Enum.map(l, &Map.new(&1, fn
...> {:code, code} -> {:product_code, code}
...> pair -> pair
...> end))
[
%{expired_at: ~U[2020-10-27 17:49:47Z], product_code: "test"},
%{expired_at: ~U[2021-07-30 13:54:11Z], product_code: "test"}
]
Notice the use of
Map.new/2
which creates a Map from the given enumerable with the elements that result from applying the given function to the enumerable
或者可能更清楚的替代方法,而不使用
Map.new/2
像这样或迭代 map 的键,可以使用 Map.delete/2
和 Map.put/3
:iex> Enum.map(l, fn %{code: code} = element ->
...> element
...> |> Map.delete(:code)
...> |> Map.put(:product_code, code)
...> end)
[
%{expired_at: ~U[2020-10-27 17:49:47Z], product_code: "test"},
%{expired_at: ~U[2021-07-30 13:54:11Z], product_code: "test"}
]
关于dictionary - Elixir:重命名字典中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63196291/