Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Map Replacing particular key values alone

Tags:

elixir

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.

Example

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?

like image 547
sdg Avatar asked Jan 20 '26 14:01

sdg


2 Answers

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}]}]
like image 104
Aleksei Matiushkin Avatar answered Jan 23 '26 16:01

Aleksei Matiushkin


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!

like image 30
Paweł Dawczak Avatar answered Jan 23 '26 17:01

Paweł Dawczak