LoginSignup
2
1

More than 5 years have passed since last update.

2つのリストをキーと値のmapとしてマージする

Last updated at Posted at 2018-01-24

Enum.into()は、リストをマージするのに、なかなか便利に使える

defmodule MapList do
    def zip( list1, list2 ), do: Enum.into( List.zip( [ list1, list2 ] ), %{} )
end

たとえば、Ectoで直接select文を流した後の結果は、columnsというリストと、rowsというリストのリストで別々のアイテムで返ってくるが、この2つをマージして、columnsの各値をキーとするmap_listに変換することができる

Ecto.Adapters.SQL.query( Livery.Repo, sql, [] )
|> Tpl.ok
|> rows 
|> Enum.map( &( MapList.zip( columns( result ), &1 ) ) )

これをPhoenixのindex.html.eexなんかでforで回すと、けっこう便利な書き方ができる

<table>
<tr>
<%= for caption <- map_list |> List.first |> Map.keys() do %>
    <th><%= caption %></th>
<% end %>
</tr>
<tr>
<%= for record <- map_list do %>
    <%= for column <- record |> Map.keys() do %>
    <td><%= record[ column ] %></td>
    <% end %>
<% end %>
</tr>
</table>

なお、列に日時型があると、上記のままではエラーになってしまうので、日時タプルから文字列への変換をしてあげる

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1