Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir check if map contains a list of keys [duplicate]

Tags:

elixir

required_keys = [ "a", "b", "c" ]

map_to_check = %{ "x" => "foo", "y" => "bar", "z" => "baz" }

Given the above required_keys list, and the map_to_check map, how can I easily test if map_to_check contains ALL the keys found in required_keys list in Elixir?

I know I can use Map.has_key?(map_to_check, "a") check if one value exist.

And trying to iterate over the required_keys gave me an error because I was using Enum.map like so:

Enum.map(required_keys, fn k -> Map.has_key?(Map.keys(map_to_check), k) end)

The above didn't work because Enum.map does not iterate over lists.

EDIT

From looking at the answers, I've noticed that the reason my solution didn't work wasn't because Enum.map couldn't iterate lists, but rather due to the fact that I was passing in a list to Map.has_key? function by calling Map.keys(map_to_check)

So the following alternative should also work:

Enum.map(required_keys, fn k -> Map.has_key?(map_to_check, k) end)
like image 279
dnshio Avatar asked Apr 24 '16 12:04

dnshio


1 Answers

Try Enum.all?/2:

required_keys |> Enum.all?(&(Map.has_key?(map_to_check, &1)))
like image 168
rossta Avatar answered Oct 20 '22 01:10

rossta