2016-11-26 31 views
0

的名單我有這樣的結構(數據來自DB):如何變換結構成地圖

%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函數內部傳遞,其中我可以訪問結構作爲@links:

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

這裏有什麼邏輯? 'videoPath'可以是一個字符串列表還是零列表? 'youTubePath'可以是字符串還是字符串列表?那麼'imgPath'呢? – Dogbert

+0

如果可能,你可以顯示'Component.html'嗎?生成這樣的列表對我來說看起來並不是一個好設計(看到模板代碼會使它更清晰)。 – Dogbert

+0

@Dogbert我需要通過在我的'Component.html中的<%= for {i,id} < - Enum.with_index(@data)do%>'枚舉的格式傳遞.eex'。 'imgPath,videoPath和youTubePath'中的每一個都是'string'或'nil'。 –

回答

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

它確實有效!但我必須承認,我不明白/遵循如何轉換工作線3至5 ... –

+0

通過閱讀文檔,我現在瞭解你的邏輯,除了這兩個:'對於<鑰匙,路徑< - 做的事 %{empty |鍵=>路徑}'。您能否指出相關信息(關於最後一行以及'for'中的兩個迭代。 –