Todd M
Todd M

Reputation: 1010

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

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.

Upvotes: 5

Views: 791

Answers (2)

CoderDennis
CoderDennis

Reputation: 13837

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.

Upvotes: 1

Onorio Catenacci
Onorio Catenacci

Reputation: 15343

This code should do what you want:

defmodule RecommendedItem do
  defstruct item: "", score: 0
end

defmodule Demo do

  defp parse_list([]), do: []

  defp parse_list([%{"item" => i, "score" => s} | tail]) do
    [%RecommendedItem{item: i, score: s} | parse_list(tail) ]
  end

  def create_recommend_list(%{"itemScores" => score_list})  do
    parse_list(score_list)
  end

end

# And this is how you'd call it.

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

l = Demo.create_recommend_list(recos)

# l = [%RecommendedItem{item: "i0", score: 0.0126078259487225},
# %RecommendedItem{item: "i3", score: 0.007569829148848128},
# %RecommendedItem{item: "i4", score: 0.007023984270125072},
# %RecommendedItem{item: "i33", score: 0.0068045477730524495}]

I hope that helps. While I think I understand what you're asking, I don't think converting each map to a struct is really what you want to do.

Upvotes: 0

Related Questions