我如何在Elixir Map中提取值

时间:2019-04-29 20:41:55

标签: elixir

假设我有这个

%{
  "contact_full_name" => ["Jane", "Joe", "Job"],
  "contact_mobile_number" => ["1234", "5678", "9012"],
  "contact_relationship" => ["sibling", "stuff", "stuff"]
}

我如何遍历该地图,    "jane, 1234, sibling""Jone, "5678", "stuff"

尝试使用

Enum.each(contact, fn {k, v} ->
  IO.puts("#{k} --> #{v}")
end)

但是会产生

contact_full_name --> JaneJoeJob
contact_mobile_number --> 123456789012
contact_relationship --> siblingstuffstuff

1 个答案:

答案 0 :(得分:6)

您可以使用Map.values/1提取地图值,然后使用Enum.zip/1压缩列表值:

contact_details = %{
  "contact_full_name"     => ["Jane", "Joe", "Job"],
  "contact_mobile_number" => ["1234", "5678", "9012"],
  "contact_relationship"  => ["sibling", "stuff", "stuff"]
}

contact_details |> Map.values() |> Enum.zip()

这将产生:

[
  {"Jane", "1234", "sibling"},
  {"Joe", "5678", "stuff"},
  {"Job", "9012", "stuff"}
]

但是,请注意,这将返回一个元组列表。您可以通过其他步骤将元组转换为列表,并使用Tuple.to_list/1映射和转换元组:

contact_details 
|> Map.values() 
|> Enum.zip() 
|> Enum.map(&Tuple.to_list/1)

哪种产量:

[
  ["Jane", "1234", "sibling"],
  ["Joe", "5678", "stuff"],
  ["Job", "9012", "stuff"]
]

希望这会有所帮助:)