Reputation: 49
How can I update all values in a map, using the values from corresponding keys of another map? For example I have the two maps bellow:
map = %{"December 2021" => 0, "November 2021" => 0, "October 2021" => 0}
map_2 = %{"December 2021" => 7, "November 2021" => 6}
And I want to update all values from map with the corresponding values from map_2, so in the end map = %{"December 2021" => 7, "November 2021" => 6, "October 2021" => 0}
I have tried:
Enum.map(map_2, fn {key, value} -> %{map | k => v} end)
I have also tried the code above with other functions like Map.update!/3 and similar ones, but they all return a list with maps for each iteration of Enum.map.
Does someone have any idea on how to do it?
Thanks in advance
Upvotes: 2
Views: 813
Reputation: 3159
The most idiomatic way to accomplish this is to use the Map.merge/2
function, which does exactly this:
Map.merge(map, map_2)
This will merge all key-value pairs from map_2
into map
.
Of course, you could write a custom version of it using Enum.reduce/3
as well as suggested by @zwippie, but this would be less efficient and more verbose.
Upvotes: 2
Reputation: 15515
I think you are looking for Enum.reduce/3. Reduce here means to reduce a collection to a single value. The collection to reduce here is map_2
. The initial/single value you start with is the original collection map
. The output is a modification of the initial value.
In this example, every key/value of map_2
is passed to a function that also expects an accumulator acc
. acc
is initialized with the initial value map
(the second argument of Enum.reduce). In this case, every value of map_2
is added to map
:
map = %{"December 2021" => 0, "November 2021" => 0, "October 2021" => 0}
map_2 = %{"December 2021" => 7, "November 2021" => 6}
Enum.reduce(map_2, map, fn {key, value}, acc ->
Map.put(acc, key, value)
end)
#> %{"December 2021" => 7, "November 2021" => 6, "October 2021" => 0}
If you want different behavior, for example don't add values from map_2
with keys that are non-existent in map
: try to change the reducer function.
Upvotes: 5