Hi,
I have the following data:
options = [
%{
id: 1,
text: "Employee",
},
%{
id: 2,
text: "Other",
}
]
and I’m looking to convert it into the following structure:
[
"Employee": "1",
"Other": "2"
]
I’m probably being stupid but I can’t figure out a way to convert it so figured I’d post here, sorry for asking such a basic question and thanks in advance!
Eiji
April 6, 2022, 10:42am
2
@CallumVass I Keyword
is a List
and has an extra syntactic sugar
like this:
[a: 5, b: 10]
Such List
contains Tuple
s with key which is always an Atom
and value which may be literally any Elixir
term.
iex(1)> [a: 5, b: 10] == [{:a, 5}, {:b, 10}]
true
The structure you show does not exists in Elixir
, but of course we can still have a Keyword
-like List
with those keys and values.
iex(1)> options = [%{id: 1, text: "Employee"}, %{id: 2, text: "Other"}]
[%{id: 1, text: "Employee"}, %{id: 2, text: "Other"}]
iex(2)> list = Enum.map(options, &{&1.text, Integer.to_string(&1.id)})
[{"Employee", "1"}, {"Other", "2"}]
Helpful resources:
Keyword documentation
Tuple documentation
Atom documentation
Enum.map/2 documentation
Integer.to_string/2 documentation
4 Likes
Thank you @Eiji - I did try this but to no avail:
options |> Enum.map(fn o -> %{o.text => o.id} end)
But your solution works, seems I was close, thanks again!
options |> Enum.map(&{&1.text, &1.id})
Eiji
April 6, 2022, 10:52am
4
Looks like you tried to create a Map
like this:
%{
"Employee" => "1",
"Other" => "2"
}
This is also possible, for example:
iex(1)> options = [%{id: 1, text: "Employee"}, %{id: 2, text: "Other"}]
[%{id: 1, text: "Employee"}, %{id: 2, text: "Other"}]
iex(2)> Enum.reduce(options, %{}, &Map.put(&2, &1.text, Integer.to_string(&1.id)))
%{"Employee" => "1", "Other" => "2"}
Helpful resources:
Map documentation
Enum.reduce/3 documentation
Map.put/3 documentation
Integer.to_string/2 documentation
1 Like