Elixir convert struct to map

user2070502 picture user2070502 · Apr 9, 2016 · Viewed 21.3k times · Source

I'm trying to convert a struct to a map to be able to clean all the nil values

I'm currently using this code

  case Nadia.get_updates  do
    {:ok, results} ->
      Map.from_struct(results)
      |> Enum.filter(fn {_, v} -> v != nil end)
      |> Enum.into(%{})

Note: Nadia.get_updates returns the following structure: https://hexdocs.pm/nadia/Nadia.Model.Update.html#t:t/0

Yet I'm always receiving the following error: no function clause matching in Map.from_struct/1

Answer

Juliano picture Juliano · Jan 19, 2017

Since v0.15 we have Map.from_struct/1 which does exactly this.

defmodule User do
  defstruct [:name]
end

Map.from_struct(%User{name: "valim"})
#=> %{name: "valim"}