Map inside a list. Search if Key and value exists and grab the entire map

First time posting on this forum so yay! I am new to Elixir and decided to post a question I been struggling on.

So there is a list and inside the list are maps. I am trying to grab the map which has key of “type” and the value of “ITEM_PURCHASED”. Others can be completely ignored. I used Map.take function but the problem is, it grabs the the first map below.

%{
  "itemId" => 1052,
  "participantId" => 8,
  "timestamp" => 1152905,
  "type" => "ITEM_DESTROYED"
},
%{ 
  "itemId" => 1052,
  "participantId" => 5,
  "timestamp" => 1153731,
  "type" => "ITEM_PURCHASED"
},
%{
  "levelUpType" => "NORMAL",
  "participantId" => 1,
  "skillSlot" => 2,
  "timestamp" => 1155348,
  "type" => "SKILL_LEVEL_UP"
},    

Cheers,

Cleanifelse

2 Likes
iex(9)> list 
[
  %{
    "itemId" => 1052,
    "participantId" => 8,
    "timestamp" => 1152905,
    "type" => "ITEM_DESTROYED"
  },
  %{
    "itemId" => 1052,
    "participantId" => 5,
    "timestamp" => 1153731,
    "type" => "ITEM_PURCHASED"
  },
  %{
    "levelUpType" => "NORMAL",
    "participantId" => 1,
    "skillSlot" => 2,
    "timestamp" => 1155348,
    "type" => "SKILL_LEVEL_UP"
  }
]
iex(10)> Enum.find(list, fn map -> map["type"] == "ITEM_PURCHASED" end)
%{
  "itemId" => 1052,
  "participantId" => 5,
  "timestamp" => 1153731,
  "type" => "ITEM_PURCHASED"
}
5 Likes

By the way, you shouldn’t be using strings, but atoms as keys for maps, and for “type” values as well

2 Likes

Thank you Eksperimental! I will keep that in mind as well. :slightly_smiling_face:

2 Likes