Get specific key values in a list of maps with Elixir?

You can map over the list and return the id using Enum.map/2

Enum.map(list_with_maps, fn (x) -> x["id"] end)
[1, 2]

You can write the same function using the capture operator:

Enum.map(list_with_maps, & &1["id"])

I prefer writing & &1["id"] as &(&1["id"]) but the parentheses are optional.


A more generic (and simpler) way of getting a subset of the keys of a Map is to use Map.take/2, which you can use like this:

map = %{"id" => 1, "name" => "a"}
Map.take(map, ["id"])
> %{"id" => 1}

As you can see, it takes an array of keys and returns a new map with only the keys you want.

Now, applying this to a list is as simple as using a map, and then using the Map.take/2 in mapper function. As has been pointed out, you can do this using either a lambda:

Enum.map(list_with_maps, fn (map) -> Map.take(map, ["id"]) end)

Or you can use a capture:

Enum.map(list_with_maps, &(Map.take(&1, ["id"])))

This will create more intermediate maps, but for most situations that won't be a problem, as Elixir is pretty smart about memory re-usage and won't actually create these objects a lot of the times, unles

Tags:

Elixir