Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Enumerate Over A Map To Produce A List of Structs

Tags:

elixir

I'm new to Elxir.

If I have the following Map

recos = %{"itemScores" => [%{"item" => "i0", "score" => 0.0126078259487225},
%{"item" => "i3", "score" => 0.007569829148848128},
%{"item" => "i4", "score" => 0.007023984270125072},
%{"item" => "i33", "score" => 0.0068045477730524495}]}

(This is a map right?)

How would I enumerate over all the itemScores in order to produce of list of RecommendationItems?

defmodule RecommendedItem do
  defstruct [:item, :score]
end 

I'm thinking it's going to invoice Enum.map(recos["itemScores"], fn->) in some way, but I'm not sure.

like image 215
Todd M Avatar asked Nov 09 '22 19:11

Todd M


1 Answers

Thanks to @zaboco's comment for pointing out that struct/2 won't work because your map has string keys instead of atom keys.

This is how to do it in a call to Enum.map:

Enum.map(recos["itemScores"], fn %{"item" => item, "score" => score} -> %RecommendedItem{item: item, score: score} end)

I tested and verified the code this time.

like image 108
CoderDennis Avatar answered Nov 15 '22 09:11

CoderDennis