I’m trying to manipulate the following map in Elixir, but I fail to get it working. I want to set a user_id
for all entries of user_sports
.
%{"zip" => "",
"location => "",
"user_sports" =>
%{"0" => %{"sport_id" => "1", "user_id" => ""},
"1" => %{"sport_id" => "1", "user_id" => ""}
}
}
As far as I understood it, the following makes it harder: The keys are “numbers”, so they aren’t stable; it’s not a single entry, there are multiple.
I have tried Map.replace
and Map.put
, but it feels like the Enum.each
prevents the results being saved in the map.
Enum.each(user_sports, fn {k, v} ->
Map.replace!(user_sports, k, %{v | "user_id" => user.id})
end)
When I tried to use them with fixed keys, it worked, but unfortunately, I never know how many entries I have.
Map.put(user_sports, "0", %{Map.get(user_sports, "0") | "user_id" => user.id})
I have also tried get_and_update(_in)
, but I was always running into the given function must return a two-element tuple or :pop, got: :ok
:
params = get_and_update_in(user_params, ["user_sports"], fn c -> Enum.each(c, fn {k, v} -> {k, %{v | "user_id" => user.id}} end) end)
I feel, I am not far way from the right solution, but I have a stupid mistake/misunderstanding.