Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to determine if a Map has certain keys

Tags:

elixir

I have a List of required keys (required_keys):

["artist", "track", "year"]

and a Map (params):

%{"track" => "bogus", "artist" => "someone"}

and I want to determine if the params has the required_keys. I'm coming from a Ruby background and iterating seems wrong for Elixir, but not sure how to pattern-match to do this.

like image 457
Midwire Avatar asked Feb 07 '23 05:02

Midwire


1 Answers

Use Enum.all?/2 and Map.has_key?/2:

iex(1)> map = %{"track" => "bogus", "artist" => "someone"}
%{"artist" => "someone", "track" => "bogus"}
iex(2)> map2 = %{"track" => "bogus", "artist" => "someone", "year" => 2016}
%{"artist" => "someone", "track" => "bogus", "year" => 2016}
iex(3)> required_keys = ["artist", "track", "year"]
["artist", "track", "year"]
iex(4)> Enum.all?(required_keys, &Map.has_key?(map, &1))
false
iex(5)> Enum.all?(required_keys, &Map.has_key?(map2, &1))
true

but not sure how to pattern-match to do this

Pattern matching is not possible if required_keys is dynamic. If it's a static list, you could use pattern matching:

iex(6)> match?(%{"artist" => _, "track" => _, "year" => _}, map)
false
iex(7)> match?(%{"artist" => _, "track" => _, "year" => _}, map2)
true
like image 196
Dogbert Avatar answered Feb 27 '23 10:02

Dogbert