Stephen
Stephen

Reputation: 3982

Iterate map and update value in elixir?

I have a map/struct data:

%{foo: "102", zoo: "103", bar: "104"}

I want to iterate the map and update the value to be integer, how should I do it?

result = %{foo: 102, zoo: 103, bar: 104}

Cheers

Upvotes: 2

Views: 2128

Answers (3)

Ankanna
Ankanna

Reputation: 777

We can achieve this using Map.new. It is simpler and self descriptive.

map = %{foo: "102", zoo: "103", bar: "104"}
Map.new(map, fn {key, value} -> {key, String.to_integer(value)} end)

# %{bar: 104, foo: 102, zoo: 103}

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

Also, with Kernel.SpecialForms.for/1 list comprehension:

for {k, v} <- %{foo: "102", zoo: "103", bar: "104"},
  into: %{},
  do: {k, String.to_integer(v)}
#⇒ %{bar: 104, foo: 102, zoo: 103}

Or, directly with Enum.reduce/3.

Enum.reduce(
  %{foo: "102", zoo: "103", bar: "104"},
  %{},
  fn {k, v}, acc ->
    Map.put(acc, k, String.to_integer(v))
  end
)
#⇒ %{bar: 104, foo: 102, zoo: 103}

Upvotes: 7

Milan Velebit
Milan Velebit

Reputation: 2027

Say that your map is defined as my_map:

Enum.into(Enum.map(my_map, fn ({key, value}) -> {key, String.to_integer(value)} end), %{})

This iterates over the map, remapping its values to Integers, then converting the resulting list of tuples into a proper Map. Note that this returns a new Map as the structures are immutable.

Upvotes: 4

Related Questions