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)
Try Enum.all?/2
:
required_keys |> Enum.all?(&(Map.has_key?(map_to_check, &1)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With