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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With