Reputation: 137
I have a function that has a Map %{}
as its param
def set_data (data) do
...
end
I am trying to update the param data
using map.put
.
data
is a flat map like so
%{
a: ...
b: ...
c: ...
}
What I have an issue with is setting a key/property in the data
map with another map that looks like this:
ModuleA.EctoSchemaMap{
some_key: nil,
another_key: ModuleB.EctoSchemaMap{
inner_key_a: "456",
inner_key_b: nil
}
}
This map above ModuleA.EctoSchemaMap
is returned from a function call like so
some_data = get_data()
So some_data
= ModuleA.EctoSchemaMap
map above.
For some reason, when I try to update the key b
in the param data
map in the function, everything will copy over that is a nil
value in the ModuleA.EctoSchemaMap
map, but the key inner_key_a
shows as nil as well, even though before some_data
shows inner_key_a
is not nil
data
|> map.put(:a, "123")
|> map.put(:b, some_data)
After doing the piping above, I was expecting data
to have :b
updated with the value
b: ModuleA.EctoSchemaMap{
some_key: nil,
another_key: ModuleB.EctoSchemaMap{
inner_key_a: "456", //I need this value to be there
inner_key_b: nil
}
}
but it is instead showing this
b: ModuleA.EctoSchemaMap{
some_key: nil,
another_key: ModuleB.EctoSchemaMap{
inner_key_a: nil, //NOT sure why this is being set as nil even though `some_data` had a value for this
inner_key_b: nil
}
}
Upvotes: 0
Views: 651
Reputation: 2201
All the data structures are immuatable in Elixir. In the code, Map.put
creates a new copy of the map with your given key-value added/updated. But it is not storing anywhere. So, reassigne the variable data_map
data_map = data_map
|> map.put(:some_key, data)
Since your have only one operation in the pipe, the recommended way to it is-
data_map = Map.put(data_map, :some_key, data)
Also note that it is Map
not map
.
Upvotes: 4