Reputation: 12443
How do I update a map which has string keys? I want to update the "brand" value.
My code (product is a map with "brand" key):
brand = URI.decode(product["brand"])
IO.inspect(brand, label: "uri decode")
brand = elem(Poison.decode(brand), 1)
IO.inspect(brand, label: "json decode")
Map.put(product, "brand", brand)
IO.inspect(product["brand"], label: "actual product brand")
outputs:
uri decode: "\"e&ggsssssaaqss\""
json decode: "e&ggsssssaaqss"
actual product brand: "%22e%26ggsssssaaqss%22"
It isn't updating product["brand"]
The actual product brand
log should equal the json decode
log if it gets updated.
What am I doing wrong?
Upvotes: 3
Views: 2176
Reputation: 8284
A more terse syntax is the | operator
my_map = %{"a" => 1, "b" => 2}
%{my_map | "a" => 100}
or also you can use the put_in
method
my_map = %{"a" => 1, "b" => 2}
put_in(my_map["a"], 100)
Upvotes: 2
Reputation: 76
If a map has string keys like so:
my_map = %{"a" => 1, "b" => 2}
You can create a new map with the changed key like this:
my_new_map = Map.put(my_map, "a", 100)
Or you can rebind the existing my_map
variable with the updated map like so:
my_map = Map.put(my_map, "a", 100)
Upvotes: 4