dictionary - Elixir:重命名字典中的键

标签 dictionary elixir key rename

我有以下 map 列表:

[
  %{
    code: "test",
    expired_at: ~U[2020-10-27 17:49:47Z],
  },
  %{
    code: "test",
    expired_at: ~U[2021-07-30 13:54:11Z],
  }
]
重命名 key 的最复杂方法是​​什么codeproduct_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/

相关文章:

count - 生产中的 Redis 扫描计数

java - 如何将值添加到 Map 中的 Set?

string - 使用文件中的下一个单词更新字典值?

java - Collections.synchronized 映射是否使 Iterator 线程安全

ios - 将 NSDictionary(带有自定义类)保存到 NSUserDefaults

elixir - 如何区分 Elixir 的 `with` 宏中的错误?

python - 读取并输出列表中使用它的行的脚本

erlang - 生产 Elixir 未找到现有原子

serialization - 为什么在反序列化 Elixir 映射时 `erl_decode` 返回 NULL?

ios - 在 Info.plist 中为通用应用程序设置 Main nib?