通过枚举迭代并提取值

时间:2017-10-27 13:08:34

标签: elixir

list_of_comboboxes=[
{"option", [{"value", ""}, {"selected", "selected"}], ["Select Color"]}, 
{"option", [{"value", "White"}, {"data", "White"}], ["White"]},
{"option", [{"value", "Red"}, {"data", "Red"}], ["Red"]},
{"option", [{"value", "Black"}, {"data", "Black"}], ["Black"]}
]

需要将上述枚举中的所有值提取到列表

4 个答案:

答案 0 :(得分:2)

以下是使用模式匹配forList.keyfind/3执行此操作的一种方法:

iex(1)> list_of_comboboxes=[
...(1)>   {"option", [{"value", ""}, {"selected", "selected"}], ["Select Color"]},
...(1)>   {"option", [{"value", "White"}, {"data", "White"}], ["White"]},
...(1)>   {"option", [{"value", "Red"}, {"data", "Red"}], ["Red"]},
...(1)>   {"option", [{"value", "Black"}, {"data", "Black"}], ["Black"]}
...(1)> ]
iex(2)> for {_, list, _} <- list_of_comboboxes,
...(2)>     {"value", value} = List.keyfind(list, "value", 0),
...(2)>     do: value
["", "White", "Red", "Black"]

即使{"value", value}不是列表中的第一项,这也会有效。

答案 1 :(得分:2)

list_of_comboboxes |>
Enum.map( fn ({_, [{_, x}, {_, _}], [_]}) -> 
          x end )

答案 2 :(得分:2)

出于好奇:

list_of_comboboxes
|> Enum.map(fn {"option", list, _} ->
     Enum.map(list, fn {k, v} -> {String.to_atom(k), v} end)[:value]
   end)
#⇒ ["", "White", "Red", "Black"]

答案 3 :(得分:1)

出于好奇心#2:

defmodule M do
  def extract({"option", [{"value", value} | _], _}), do: value
end
Enum.map(list_of_comboboxes, &M.extract/1)
#⇒ ["", "White", "Red", "Black"]

这看起来可能更糟,但实际上它提供了更大的灵活性:可以调整实现细节(M.extract/1),使集成代码(Enum.map)保持不变。

这样代码就更加模块化了。例如。可以在List.keyfind/3中使用@Dogbert提出的M.extract/1以获得更好的互操作性,而主要代码保持不变。