假设这个data_set,
%{"ACTION" => "avail.datacenters",
"DATA" => [%{"ABBR" => "dallas", "DATACENTERID" => 2,
"LOCATION" => "Dallas, TX, USA"},
%{"ABBR" => "fremont", "DATACENTERID" => 3,
"LOCATION" => "Fremont, CA, USA"},
%{"ABBR" => "atlanta", "DATACENTERID" => 4,
"LOCATION" => "Atlanta, GA, USA"},
%{"ABBR" => "newark", "DATACENTERID" => 6, "LOCATION" => "Newark, NJ, USA"},
%{"ABBR" => "london", "DATACENTERID" => 7,
"LOCATION" => "London, England, UK"},
%{"ABBR" => "tokyo", "DATACENTERID" => 8, "LOCATION" => "Tokyo, JP"},
%{"ABBR" => "singapore", "DATACENTERID" => 9,
"LOCATION" => "Singapore, SG"},
%{"ABBR" => "frankfurt", "DATACENTERID" => 10,
"LOCATION" => "Frankfurt, DE"},
%{"ABBR" => "shinagawa1", "DATACENTERID" => 11,
"LOCATION" => "Tokyo 2, JP"}], "ERRORARRAY" => []}}
在Ruby中,我可以做到
formatted_array_of_hashes = data_set.each.map{ |h| { h["LOCATION"] => h["DATACENTERID"] }}
然后
merged_hash = Hash[*formatted_array_of_hashes.map(&:to_a).flatten]
...我将在select标签中使用location,datacenterid。
请问我如何在Elixir中实现类似的东西?
任何指向正确方向的指针都将受到高度赞赏
答案 0 :(得分:0)
您可以使用for
,在do
中返回2个元组并将其into: %{}
:
map = for %{"LOCATION" => k, "DATACENTERID" => v} <- data_set, into: %{}, do: {k, v}
但是,如果要将其与Phoenix.HTML.Form.select/4
一起使用,则无需构建地图。您可以传递元组列表。这样你就不会像使用地图那样丢失元素的排序,因为地图是无序的。
select _, _, for(%{"LOCATION" => k, "DATACENTERID" => v} <- data_set, do: {k, v})
旁注:您的Ruby代码也可以简化为:
hash = data_set.map { |h| [h["LOCATION"], h["DATACENTERID"]] }.to_h