Oumak81
Oumak81

Reputation: 33

Updating a nested map in Elixir

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.

Upvotes: 3

Views: 4191

Answers (2)

Scott Thompson
Scott Thompson

Reputation: 23701

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

Upvotes: 2

Dogbert
Dogbert

Reputation: 222158

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)

Upvotes: 1

Related Questions