Another option is to use the get_in
function and leveraging the Access
module. The Access module lets you build expressive ways of dealing with nested data structures.
To get a list of values at "id"
you could run:
get_in(list_with_maps, [Access.all, "id"])
Passing Access.all
as the first element in the list, followed by "id"
tells get_in
to return all list_with_maps
's "id"
value.
It may seem like overkill for this example, but if your structure looked like:
list_with_maps = [%{"id" => 1, "identities" => [%{"name" => "a"}, %{"name" => "Secret A"}]}, %{"id" => 2, "identities" => [%{"name" => "b"},%{"name" => "Secret B"}]}]
We could get all of the names with:
get_in(list_with_maps, [Access.all, "identities", Access.all, "name"])
# [["a", "Secret A"], ["b", "Secret B"]]