Reputation: 1400
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"]}
]
Need to extract all the values in the above Enum to a list
Upvotes: 1
Views: 703
Reputation: 121010
Just out of curiosity #2:
defmodule M do
def extract({"option", [{"value", value} | _], _}), do: value
end
Enum.map(list_of_comboboxes, &M.extract/1)
#⇒ ["", "White", "Red", "Black"]
This might look worse, but in fact it gives more flexibility: one might adjust the implementation details (M.extract/1
) leaving the integration code (Enum.map
) intact.
That way the code stays more modular. E.g. one might use the List.keyfind/3
proposed by @Dogbert in M.extract/1
for better interoperability, while the main code stays as it was.
Upvotes: 1
Reputation: 121010
Just out of curiosity:
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"]
Upvotes: 3
Reputation: 3069
list_of_comboboxes |>
Enum.map( fn ({_, [{_, x}, {_, _}], [_]}) ->
x end )
Upvotes: 2
Reputation: 222378
Here's one way to do this using pattern matching, for
, and List.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"]
This will work even if {"value", value}
is not the first item of the list.
Upvotes: 2