Hi, how to convert a list like this to nested map in elixir ?
[
{"_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"]}
]}}
]
I would do it something like this:
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
And then call it with just
transform/1
And the result would be something like:
%{
"App-Version" => "version_here",
"Body" => %{
"CurrentTime" => "2023-02-23T16:40:13+05:30",
"Identification" => %{
"A" => "A-Val",
"B" => "B-Val",
"C" => "C-Val",
"D" => "D-Val"
},
"Names" => ["Name1", "Name2"]
},
"Method" => "method-here",
"TX-ID" => "tx-id-here",
"_id" => "idhere"
}
3 Likes
Thanks, solution is concise
hlx
4
May I offer an alternative:
def transform([_ | _] = list) do
Map.new(list, fn
{k, [{_, _} | _] = v} -> {k, transform(v)}
{k, {[_ | _] = v}} -> {k, transform(v)}
{k, v} -> {k, v}
end)
end
4 Likes
Map.new with fn method is more concise . Thanks
I tried this initially, but didn’t complete successfully.
1 Like