Delete map from list of maps where we don't care about map value for some key

I have List like such:

list = [%{“key1” => “allow”}, %{“key2” => “deny”}, %{“key3” => “allow”}]

I’d like to remove the map in the list that has a key like for example:

k = “key2”

by doing:

List.delete(list, %{k => _ })

I cannot underscore the value for k which I don’t care about.

I also tried Regex like:

List.delete(list, %{k => %BSON.Regex{pattern: “allow|deny”, options: “s”}})

You should use Enum.filter for this, or Enum.reject…

iex> list = [%{"key1" => "allow"}, %{"key2" => "deny"}, %{"key3" => "allow"}]
iex> list |> Enum.reject(&Map.has_key?(&1, "key2"))
[%{"key1" => "allow"}, %{"key3" => "allow"}]
1 Like

I don’t know about any performance differences, but this would be a handy place to use Kernel.match? It gets back to your intuition of using underscore for the value you don’t care about.

iex(13)> list = [%{"key1" => "allow"}, %{"key2" => "deny"}, %{"key3" => "allow"}]
iex(14)> k = "key2"
iex(15)> Enum.reject(list, &match?(%{^k => _}, &1))
[%{"key1" => "allow"}, %{"key3" => "allow"}]