Skip to content

Instantly share code, notes, and snippets.

@stefanluptak
Last active January 3, 2022 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanluptak/7c559b3e185a738e4d91ca96a4c82426 to your computer and use it in GitHub Desktop.
Save stefanluptak/7c559b3e185a738e4d91ca96a4c82426 to your computer and use it in GitHub Desktop.

Struct list to map list

Section

defmodule User do
  defstruct [:id, :name, :role, :age]
end
{:module, User, <<70, 79, 82, 49, 0, 0, 7, ...>>, %User{age: nil, id: nil, name: nil, role: nil}}
users_list = [
  %User{id: 1, name: "Alice", role: "user", age: 20},
  %User{id: 2, name: "Bob", role: "admin", age: 30},
  %User{id: 3, name: "John", role: "editor", age: 40}
]
[
  %User{age: 20, id: 1, name: "Alice", role: "user"},
  %User{age: 30, id: 2, name: "Bob", role: "admin"},
  %User{age: 40, id: 3, name: "John", role: "editor"}
]
Enum.map(users_list, fn user_struct ->
  Map.take(user_struct, [:id, :name])
end)
[%{id: 1, name: "Alice"}, %{id: 2, name: "Bob"}, %{id: 3, name: "John"}]
Enum.map(users_list, &Map.take(&1, [:id, :name]))
[%{id: 1, name: "Alice"}, %{id: 2, name: "Bob"}, %{id: 3, name: "John"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment