Last active
June 10, 2020 13:12
-
-
Save BenSchZA/ad37fa027565344f35e4fb961da5602e to your computer and use it in GitHub Desktop.
Flatten a nested map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data = %{"key1" => %{sub_key: :a}, "key2" => %{"sub_key1" => %{"sub_key" => "a"}, "sub_key2" => :a}} | |
defmodule Flatten do | |
def flat(data, acc) when is_bitstring(data) or is_atom(data), do: {acc, data} | |
def flat({key, value}, acc) do | |
flat(value, | |
case acc do | |
"" -> key | |
_ -> acc <> "." <> "#{key}" | |
end | |
) | |
end | |
def flat(data, acc) do | |
case Enum.map(data, fn x -> | |
flat(x, acc) | |
end) do | |
[result|[]] -> result | |
[result] -> result | |
result -> result | |
end | |
end | |
end | |
data | |
|> Enum.map(fn entry -> | |
Flatten.flat(entry, "") | |
end) | |
|> IO.inspect | |
# [{"key1.sub_key", :a}, [{"key2.sub_key1.sub_key", "a"}, {"key2.sub_key2", :a}]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment