Bitwise
Bitwise

Reputation: 8451

Update nested map

I have this map:

%{project: %{title: "Frank's Project"}}

I want to update the map to look like this:

%{project: %{title: "Frank's Project", subtitle: "another one"}}

How can I do this?

My previous attempt didn't work:

Map.put_new(params[:project], :subtitle, "another one")

returned this:

%{starterTopic: "garden", title: "Frank's Project"}

Which is not quite correct.

Upvotes: 1

Views: 67

Answers (2)

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

You can use Kernel.put_in/3:

iex(1)> map = %{project: %{title: "Frank's Project"}}
%{project: %{title: "Frank's Project"}}
iex(2)> map = put_in(map, [:project, :subtitle], "another one")
%{project: %{subtitle: "another one", title: "Frank's Project"}}

Upvotes: 4

Brett Beatty
Brett Beatty

Reputation: 5983

Elixir has a convenience macro in Kernel (automatically imported) called put_in/2 (or there's put_in/3, which is a function alternative and probably a little easier to understand what's going on).

iex> map = %{project: %{title: "Frank's Project"}}
%{project: %{title: "Frank's Project"}}
iex> put_in(map.project[:subtitle], "another_one")
%{project: %{subtitle: "another_one", title: "Frank's Project"}}

Upvotes: 4

Related Questions