Updating a nested map in Elixir

纵饮孤独 提交于 2019-12-13 15:39:38

问题


I have a 2-level-nested map, how can I update each value on the 2nd level? Right now I'm doing this:

  items = Enum.map(items, fn(a) ->
    a.items2 = Enum.map(a.items2, fn(a2) ->
      Map.put(x2, :some_key, 123) 
    end)

    a
  end)

An error:

cannot invoke remote function "a.items2/0" inside match.

I basically know what this means, but how to fix it?

Note that a.items2 might also has a nested map in itself.


回答1:


You can use Map.put outside as well:

items = Enum.map(items, fn(a) ->
  Map.put(a, :items2, Enum.map(a.items2, fn(a2) ->
    Map.put(x2, :some_key, 123) 
  end)
end)

or the map update syntax:

items = Enum.map(items, fn(a) ->
  %{a |
    items2: Enum.map(a.items2, fn(a2) ->
      Map.put(x2, :some_key, 123) 
    end)}
end)



回答2:


Enum.map(items, fn({k,v}) ->
  {k, put_in(v, [:items2, :some_key], 123)}    
end)


来源:https://stackoverflow.com/questions/43716688/updating-a-nested-map-in-elixir

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!