代码之家  ›  专栏  ›  技术社区  ›  BeniaminoBaggins

elixir-更新具有字符串键的映射

  •  1
  • BeniaminoBaggins  · 技术社区  · 7 年前

    如何更新具有字符串键的映射?我想更新“品牌”价值。

    我的代码(产品是带有“品牌”键的地图):

      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")
    

    输出:

    uri decode: "\"e&ggsssssaaqss\""
    json decode: "e&ggsssssaaqss"
    actual product brand: "%22e%26ggsssssaaqss%22"
    

    它没有更新 product["brand"]

    这个 actual product brand 日志应等于 json decode 如果更新了就记录下来。

    我做错什么了?

    2 回复  |  直到 7 年前
        1
  •  1
  •   timbuckley    7 年前

    如果映射具有这样的字符串键:

    my_map = %{"a" => 1, "b" => 2}
    

    您可以使用如下更改的键创建新映射:

    my_new_map = Map.put(my_map, "a", 100)
    

    或者您可以重新绑定现有的 my_map 更新后的映射变量如下:

    my_map = Map.put(my_map, "a", 100)
    
        2
  •  0
  •   intentionally-left-nil    7 年前

    更简洁的语法是运算符

    my_map = %{"a" => 1, "b" => 2}
    %{my_map | "a" => 100}
    

    也可以使用 put_in 方法

    my_map = %{"a" => 1, "b" => 2}
    put_in(my_map["a"], 100)