0
votes

Let's say I have this map

old = %{stuff: %{old: 123}}

How do I update the key stuff:?

I have this other map:

new = %{stuff: %{new: 321}}

With Map.put it will override stuff key and I also tried Map.merge but it doesnt merge, it overrides the key with the second map

iex(22)> Map.merge(test, new)
%{stuff: %{new: 321}}

I would like to have something like:

%{stuff: %{old: 123, new: 321}}
1

1 Answers

3
votes

Two ways I can think of:

  1. Use update_in:

    iex(1)> old = %{stuff: %{old: 123}}
    %{stuff: %{old: 123}}
    iex(2)> update_in(old, [:stuff], &Map.put(&1, :new, 321))
    %{stuff: %{new: 321, old: 123}}
    
  2. Use Map.merge/3 which merges the two values using Map.merge/2:

    iex(3)> new = %{stuff: %{new: 321}}
    %{stuff: %{new: 321}}
    iex(4)> Map.merge(old, new, fn k, v1, v2 -> Map.merge(v1, v2) end)
    %{stuff: %{new: 321, old: 123}}