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


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}]

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 =, &{&1.text, Integer.to_string(&})
[{"Employee", "1"}, {"Other", "2"}]

Helpful resources:

  1. Keyword documentation
  2. Tuple documentation
  3. Atom documentation
  4. documentation
  5. Integer.to_string/2 documentation

Thank you @Eiji - I did try this but to no avail:

options |> o -> %{o.text =>} end)

But your solution works, seems I was close, thanks again!

options |>{&1.text, &})

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(&
%{"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