How to update the value of a particular key in a map?

I have a map with multiple key-value pairs.

type: 11,
foo: “bing”,
bar: “bang”,
baz: “bop”

I want to transform the value of the type key with a string depending on what the integer is.
For instance, if the integer is 11, the value would become “Red” in the new map. If the integer is 14, the value would become “Blue”. The rest of the key-value pairs in the map should remain untouched.

type: “Red”,
foo: “Bing”,
bar: “Bang”,
baz: “Bop”

How do I accomplish this?

What have you tried so far?

I’m pretty new to Elixir so I’m still trying to get my head around a lot of the concepts. I’ve tried creating a function with a new map where each integer corresponds to a particular key but I don’t understand how to utilize this new map.

def convert_integer_to_string(map) do
1 => map[“Red”]
11 => map[“Blue”]
13 => map[“Orange”]

how about something like

def translate(%{type: id} = map}) do
  mapping = %{1 => "red", 2 => "blue"}
  %{map | type: mapping[id]}

if is a constant low number of mappings, maybe you could use a tuple {“red”, “green”, “blue”} and access it with elem(mapping, id)

Works perfectly! Thank you!

I think it would be more idiomatic to use Map.update/4 (docs) (or maybe Map.update!/3)

1 Like