Getting the value of a nested map in erlang

Viewed 1065

I have a nested map in erlang and I can't figure of how to get the value of a key from it properly.

A = #{"key1" => "val1", "key2" => #{"key3"=>"val3", "key4" => #{"key5" => "val5"}}},

I want to extract the value of key5 and so far I've tried this.

    A = #{"key1" => "val1", "key2" => #{"key3"=>"val3", "key4" => #{"key5" => "val5"}}},
    S = maps:get("key2", A),
    SS = maps:get("key4", S),
    Val = maps:get("key5", SS),
    Val.

I know it's working but I'm pretty sure there is a better way to do it!

2 Answers

You can use pattern matching to extract the value of key5:

A = #{"key1" => "val1", "key2" => #{"key3" => "val3", "key4" => #{"key5" => "val5"}}},
#{"key2" := #{"key4" := #{"key5" := Value}}} = A,
Value.

You can try create recursive function, eg:

-module(nm).

-export([nested_map/0]).

-define(KEY, "key5").

nested_map() ->
  Map =   #{"key1" => "val1", "key2" => #{"key3"=>"val3", "key4" => #{"key5" => "val5"}}},
  get_val(maps:keys(Map), Map, ?KEY).

get_val([], _, _) ->
  undefined;
get_val(_, #{?KEY := Val}, ?KEY) ->
  Val;
get_val([H|T], Map, Key) ->
  case is_map(maps:get(H, Map)) of
    true -> 
      NewMap = maps:get(H, Map),
      get_val(maps:keys(NewMap), NewMap, Key);
    false ->
      get_val(T, Map, Key)
  end.

In shell:

1> c(nm).
{ok,nm}
2> nm:nested_map().
"val5"
3> 
Related