Elixir

入れ子になったデータを取得する

引数指定したキーでmapを掘り下げる に触発されて書いています.

入れ子になったデータを取得するのには Kernel.get_in/2Access を使うと便利です.

# An example to get a value from nested data structure with using Kernel.get_in/2 and Access module

map = %{a: [1,2,3], b: %{"x" => "X", "y" => "Y"}, c: {:i, :j}}
IO.puts "map # => #{inspect map}"

key=:a
IO.puts "key # => #{inspect key}"
IO.puts "get_in(map, [key]) # => #{inspect get_in(map, [key])}"
IO.puts "get_in(map, [key, Access.at(1)]) # => #{inspect get_in(map, [key, Access.at(1)])}"

IO.puts "========"

key=:b
IO.puts "key # => #{inspect key}"
IO.puts "get_in(map, [key]) # => #{inspect get_in(map, [key])}"
IO.puts "get_in(map, [key, Access.key(\"y\")]) # => #{inspect get_in(map, [key, Access.key("y")])}"

IO.puts "========"

key=:c
IO.puts "key # => #{inspect key}"
IO.puts "get_in(map, [key]) # => #{inspect get_in(map, [key])}"
IO.puts "get_in(map, [key, Access.elem(1)]) # => #{inspect get_in(map, [key, Access.elem(1)])}"

を実行すると

map # => %{a: [1, 2, 3], b: %{"x" => "X", "y" => "Y"}, c: {:i, :j}}
key # => :a
get_in(map, [key]) # => [1, 2, 3]
get_in(map, [key, Access.at(1)]) # => 2
========
key # => :b
get_in(map, [key]) # => %{"x" => "X", "y" => "Y"}
get_in(map, [key, Access.key("y")]) # => "Y"
========
key # => :c
get_in(map, [key]) # => {:i, :j}
get_in(map, [key, Access.elem(1)]) # => :j

という感じです.

コードはwandboxに置いたので改造してお試しください.
https://wandbox.org/permlink/06RBC9YjTx4Wj7HN