I have a Map in Elixir which maps from string keys to a value which is a list of attributes. How can I remove the items which do not meet the criteria as I enumerate through the Map?
The map looks like this:
%{"A" => [needed: true], "B" => [needed: false]}
In this case I would check each key/value pair and only keep the ones with needed: true
I have tried doing different combinations of using Enum.map and Enum.each so far.
When you need to filter values out of an enumerable like a Map, Enum.filter/2 is your friend. The trick is that you need to sort of "reassemble" the result back into a map.
%{"A" => [needed: true], "B" => [needed: false]}
|> Enum.filter(fn {_, v} -> Keyword.get(v, :needed) end)
|> Enum.into(%{})
# Result:
%{"A" => [needed: true]}
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