将具有整数的哈希转换为具有哈希的列表

时间:2019-02-11 03:47:46

标签: elixir

什么是转换此哈希的最佳方法:

%{
    "0" => [
        %{"foo" => 1, "baz" => 10}
    ], 
    "1" => [
        %{"foo" => 2, "baz" => 11}
    ]
}

到这样的列表?

[
    %{"foo" => 1, "baz" => 10},
    %{"foo" => 2, "baz" => 11}
]

2 个答案:

答案 0 :(得分:3)

虽然Map.values/2肯定可以工作,但是Kernel.SpecialForms/1理解可能是一种更灵活的方法,因为它允许您就地过滤和/或修改结果。

input = %{
  "0" => [
    %{"foo" => 1, "baz" => 10}
  ], 
  "1" => [
    %{"foo" => 2, "baz" => 11}
  ]
}

for {_, [map]} <- input, do: map
#⇒ [%{"baz" => 10, "foo" => 1}, %{"baz" => 11, "foo" => 2}]

如果您期望值中的每个列表中的个以上个元素,请使用Enum.reduce/3

Enum.reduce(input, [], fn {_, maps}, acc -> acc ++ maps end)
#⇒ [%{"baz" => 10, "foo" => 1}, %{"baz" => 11, "foo" => 2}]

另一种可能性是使用Enum.flat_map/2

Enum.flat_map(input, &elem(&1, 1))
#⇒ [%{"baz" => 10, "foo" => 1}, %{"baz" => 11, "foo" => 2}]

FWIW,使用Map.values/1的解决方案(不推荐):

input
|> Map.values()
|> Enum.flat_map(& &1)
#⇒ [%{"baz" => 10, "foo" => 1}, %{"baz" => 11, "foo" => 2}]

答案 1 :(得分:0)

original = %{
    "0" => [
        %{"foo" => 1, "baz" => 10}
    ], 
    "1" => [
        %{"foo" => 2, "baz" => 11}
    ]
}

values_from_original = original |> Map.values

result = for e <- values_from_original, do: e |> Enum.at(0)