Skip to content

Instantly share code, notes, and snippets.

@BenSchZA
Last active June 10, 2020 13:12
Show Gist options
  • Save BenSchZA/ad37fa027565344f35e4fb961da5602e to your computer and use it in GitHub Desktop.
Save BenSchZA/ad37fa027565344f35e4fb961da5602e to your computer and use it in GitHub Desktop.
Flatten a nested map
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