如何将嵌套属性列表(键不是原子)转换为 Elixir 中的映射?

问题描述 投票:0回答:1

我有以下清单

nl = 
[
  {"_id", "idhere"},
  {"App-Version", "version_here"},
  {"TX-ID", "tx-id-here"},
  {"Method", "method-here"},
  {"Body",
   {[
      {"Identification",
       [
         {"A", "A-Val"},
         {"B", "B-Val"},
         {"C", "C-Val"},
         {"D", "D-Val"}
       ]},
      {"CurrentTime", "2023-02-23T16:40:13+05:30"},
      {"Names", ["Name1", "Name2"]}
    ]}}
]

如何在 Elixir 中将其转换为嵌套地图?

我尝试使用 Map.new,但我是 Elixir 的新手,无法通过。

elixir
1个回答
0
投票

从 elixirforum 得到解决方案(由 andreaseriksson 回答)

  def transform([{_, _}|_] = list) do
    Enum.reduce(list, %{}, fn {key, val}, map ->
      Map.put(map, key, transform(val))
    end)
  end
  def transform({[{_, _}|_] = list}), do: transform(list)

  def transform(val), do: val

https://elixirforum.com/t/how-to-convert-nested-property-list-having-string-keys-to-elixir-nested-map/54093

© www.soinside.com 2019 - 2024. All rights reserved.