DimWell
Hi,
I am relatively new to Elixir and need a support from more advanced users.
I try to do a simple thing → Flatten Map
But Elixir and functional programming in general is a bit new to me.
I found online a solution, but it looks overcomplicated.
I wonder if maybe there is a solution out of the box provided by the language.
I tried to find something like Map.flatten(%{a: 1, %{b: 2}}) but with no success.
It would be great if you could advice that is the best practice ?
Meanwhile, I found the solution online, please see the code below.
defmodule Json do def flatten(%{} = json) do json |> Map.to_list() |> to_flat_map(%{}) end def flatten(%{} = json) when json == %{}, do: %{} defp to_flat_map([{_k, %{} = v} | t], acc), do: to_flat_map(Map.to_list(v), to_flat_map(t, acc)) defp to_flat_map([{k, v} | t], acc), do: to_flat_map(t, Map.put_new(acc, k, v)) defp to_flat_map([], acc), do: acc end %{id: "1", foo: %{bar: %{qux: "hello world"}, baz: 123}} |> Json.flatten() |> IO.inspect() # %{baz: 123, id: "1", qux: "hello world"}
Currently, due to a lack of knowledge I can’t evaluate this solution.
I would highly appreciate if someone could comment on the above code and mention good and bad points ?
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
I’m aware of 2 such projects, are there others?
git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
Hi everyone.
My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
Hello folks!
So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
How Can I Optimise Compile Time Dependencies
I have been building an elixir application for about 2 years now. Many modules and files ha...
New
Hi,
we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
Other Trending Topics
Mojoler v0.1.0 is on Hex. It lets you code Mojo NIFs.
v0.1.0 is a work in progress.
I’m hoping Mojoler will give us BEAM developers a w...
New
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself.
My main conc...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #ai
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #hex











Showing Posts 1 to 9- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
benwilson512
Can you speak a bit about your use case? What do you want to do if sub-maps include the same key as a parent map ie:
%{foo: %{bar: 1}, bar: 2}DimWell
Wow, thanks for super fast reply !
In my scenario it is impossible that that sub maps would include same key/s as parent map.
All keys are always unique.
benwilson512
Are there any datastructures other than maps, like lists?
DimWell
Hm… I don’t think so.
I see more background information is needed.
Here is explanation that I am doing.
Here I receive a map, that contains other maps - sub maps.
Before, I can proceed further I need to flatten the map.
benwilson512
Here is a slightly simpler implementation that you may be able to evaluate more easily:
DimWell
Thank your for the example, I really appreciate!
Yes, your example has more clear process flow.
But, one step is still not very obvious to me.
First of all, I checked what data type I receive from Poison, and it is a list.
So, some changes needs to be applied:
So, the process flow is the following:
please correct me if I am wrong.
This function receives 2 arguments, list and accumulator.
List is split into: Head | Tail , this way we take first item of the list.
At the same time we pattern Head with {_k, v} and then check if v is a map.
Then we know that “v” is a map, so we convert it to list.
Then ** do_flatten** for subbtree → this goes recursevly until reaches the point that it maches: [], acc and then acc is returned.
Then:
Here we take list of subtree and join with Tail (rest) and repeat the process passing, list with accumulator. So far seems clear to me…
The only question left, when last function is called ?
In which scenario the pattern match will be matched ?
While I was re-reading my reply understood, that if v is not a map, then the last function is executed.
Then we call do_flatten and pass Tail (rest) as a first argument, and a list by using kv as Head and acc as Tail ?
I would highly appreciate if you could correct me if my understanding is wrong.
DimWell
I spend few more minutes, and finally understood, that we converted the map to list, and therefore we don’t need to pattern match to map %{k, v}.
Furthermore, no changes were needed.
As according to steps I described, I enumerate the list and take the Map as each item, therefore your code is exactly that I need.
Thank you very much , one more time!
idi527
You don’t pattern match maps with
%{ _k, v }, you do it with%{^k => v}.Note the pin.
DimWell
In this scenario, I realised that I don’t need to pattern match to map.
But in other case scenario, I would definitely forgot about the pin.
Definitely need to make a note about the pin :slight_smile
Thank you for the advise!