Convert list of struct to keyword list (I think?)

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! :slight_smile:

@CallumVass I Keyword is a List and has an extra syntactic sugar like this:

[a: 5, b: 10]

Such List contains Tuples 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:

  1. Keyword documentation
  2. Tuple documentation
  3. Atom documentation
  4. Enum.map/2 documentation
  5. 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})

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:

  1. Map documentation
  2. Enum.reduce/3 documentation
  3. Map.put/3 documentation
  4. Integer.to_string/2 documentation
1 Like