假设我有这个
%{
"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
答案 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"]
]
希望这会有所帮助:)