Paulo Janeiro
Paulo Janeiro

Reputation: 3211

How to transform a struct into a list of maps

I have this struct (data comes from DB):

%MyProj.Event{imgPath: ["images/1.jpg", "images/2.jpg", "images/3.jpg"], videoPath: "video/1.mpg", youTubePath: nil}

I need to convert it to a list of maps/keyword lists (like this):

[
  %{imgPath: "images/1.jpg", videoPath: nil, youTubePath: nil},
  %{imgPath: "images/2.jpg", videoPath: nil, youTubePath: nil},
  %{imgPath: "images/3.jpg", videoPath: nil, youTubePath: nil},
  %{imgPath: nil, videoPath: "video/1.mpg", youTubePath: nil}
]

This is to be converted and passed inside a render function where I have access to the Struct as @links:

<%= render MyProj.ModulesView, "Component.html",
    data: @links
%>

Upvotes: 1

Views: 910

Answers (1)

Dogbert
Dogbert

Reputation: 222088

I'd do it like this:

defmodule MyProj.Event do
  defstruct [:imgPath, :videoPath, :youTubePath]

  def convert(%MyProj.Event{} = event) do
    keys = [:imgPath, :videoPath, :youTubePath]
    empty = for key <- keys, into: %{}, do: {key, nil}
    for key <- keys, path <- List.wrap(Map.get(event, key)) do
      %{empty | key => path}
    end
  end
end
iex(1)> struct = %MyProj.Event{imgPath: ["images/1.jpg", "images/2.jpg", "images/3.jpg"], videoPath: "video/1.mpg", youTubePath: nil}
%MyProj.Event{imgPath: ["images/1.jpg", "images/2.jpg", "images/3.jpg"],
 videoPath: "video/1.mpg", youTubePath: nil}
iex(2)> MyProj.Event.convert(struct)
[%{imgPath: "images/1.jpg", videoPath: nil, youTubePath: nil},
 %{imgPath: "images/2.jpg", videoPath: nil, youTubePath: nil},
 %{imgPath: "images/3.jpg", videoPath: nil, youTubePath: nil},
 %{imgPath: nil, videoPath: "video/1.mpg", youTubePath: nil}]

Upvotes: 1

Related Questions