Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging Elixir maps

Tags:

maps

elixir

how can I merge those 2 Elixir maps:

foo = %{a: 1, b: 2, c: [%{d: 3, e: 4}, %{d: 5, e: 6}]}
bar = %{a: 1, b: 2, c: [%{d: 7, e: 8}, %{d: 9, e: 0}]}

... to get the following result:

%{a: 1, b: 2, c: [%{d: 3, e: 4}, %{d: 5, e: 6}, %{d: 7, e: 8}, %{d: 9, e: 0}]}

Simple Map.merge(foo,bar) doesn't do it in the way since value of c is a list.

Thank you in advance! Christoph

like image 414
ctp Avatar asked Oct 20 '25 09:10

ctp


1 Answers

Use Map.merge/3:

Map.merge(foo, bar, fn
  _k, v1, v2 when is_list(v1) and is_list(v2) -> v1 ++ v2 # lists
  _k, %{} = v1, %{} = v2 -> Map.merge(v1, v2)             # maps
  _k, v1, v1 -> v1                                        # equals
  _k, v1, v2 -> {v1, v2}                                  # non-equals
end)
#⇒ %{a: 1, b: 2,
#    c: [%{d: 3, e: 4}, %{d: 5, e: 6}, %{d: 7, e: 8}, %{d: 9, e: 0}]}

You did not specify the rule to merge anything save for lists, but the above might be easily extended to handle whatever. Now it understands lists, maps, equal values, and non-equal values.

like image 108
Aleksei Matiushkin Avatar answered Oct 22 '25 04:10

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!