Get values from nested maps

I am new to elixir.I have nested map like this:

       "select" =>  %{"customer" => %{"limit" => 10,
        "order" => %{"field1" => "desc", "field2" => "asc"}, "select" => ["id"],
           "where" => %{"id" => 10}}

I want to fetch the where . How can i do that?

2 Likes
iex(1)> map = %{1 => %{2 => %{3 => :foo}}}
%{1 => %{2 => %{3 => :foo}}}
iex(2)> map[1]
%{2 => %{3 => :foo}}
iex(3)> map[1][2]
%{3 => :foo}
iex(4)> map[1][2][3]
:foo
7 Likes

You can use the get_in/2 function from the kernel module for doing this (docs)

12 Likes

Simply you can obtain it by three ways:

1 - as NobbZ stated by accesing map directly:

map   = %{"select" => %{"customer" => %{"limit" => 10, "order" => %{"field1" => "desc", "field2" => "asc"}, "select" => ["id"], "where" => %{"id" => 10}}}}
where = map["select"]["customer"]["where"]

2 - as swelham stated by using special method Kernel.get_in/2:

map   =  %{"select" => %{"customer" => %{"limit" => 10, "order" => %{"field1" => "desc", "field2" => "asc"}, "select" => ["id"], "where" => %{"id" => 10}}}}
where = get_in(map, ["select", "customer", "where"])

3 - or by pattern matching:

%{"select" => %{"customer" => %{"where" => where}}} = %{"select" => %{"customer" => %{"limit" => 10, "order" => %{"field1" => "desc", "field2" => "asc"}, "select" => ["id"], "where" => %{"id" => 10}}}}
18 Likes