如何将结构转换为地图列表

时间:2016-11-26 10:52:36

标签: elixir phoenix-framework

我有这个结构(数据来自数据库):

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

我需要将其转换为地图/关键字列表列表(如下所示):

[
  %{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}
]

这将被转换并传递到render函数中,我可以访问Struct作为@links:

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

1 个答案:

答案 0 :(得分:1)

我会这样做:

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}]