I have an Elixir list of map in which I want to replace some values
map = [
%{id: 1, users: [%{m_value: 2, n_value: 2}]},
%{id: 2, users: [%{m_value: 4, n_value: 5}]},
%{id: 3, users: [%{m_value: 3, n_value: 4}]}
]
In this map I want to replace all the values of m_value and n_value alone.
I want to multiply all the m_value by 2 and all the n_value by 3
So my final output will be:
map = [
%{id: 1, users: [%{m_value: 4, n_value: 6}]},
%{id: 2, users: [%{m_value: 8, n_value: 15}]},
%{id: 3, users: [%{m_value: 6, n_value: 12}]}
]
Do you have suggestions on how to achieve this?
One cannot replace anything in everything in Elixir (with some very rare restrictions, like process dictionary, but this is definitely out of scope here.)
Everything in Elixir is immutable. Any code that looks like “updating” map, simply produces a new map.
One might go with Kernel.SpecialForms.for/1 comprehension:
for %{users: [%{m_value: mv, n_value: nv}]} = m <- map,
do: %{ m | users: [%{m_value: mv * 2, n_value: nv * 3}]}
#⇒ [
# %{id: 1, users: [%{m_value: 4, n_value: 6}]},
# %{id: 2, users: [%{m_value: 8, n_value: 15}]},
# %{id: 3, users: [%{m_value: 6, n_value: 12}]}]
I assume your valid map is as follows:
map = [
%{id: 1, users: [%{m_value: 2, n_value: 2}]},
%{id: 2, users: [%{m_value: 4, n_value: 5}]},
%{id: 3, users: [%{m_value: 6, n_value: 12}]}
]
please note this is a List of Maps
Then, you could try an update_in when iterating through the elements in the list:
Enum.map(
map,
fn el ->
el
|> update_in([:users, Access.all(), :m_value], fn val -> val * 2 end)
|> update_in([:users, Access.all(), :n_value], fn val -> val * 3 end)
end
)
Hope that helps!
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