Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir convert struct to map

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

like image 312
user2070502 Avatar asked Apr 09 '16 04:04

user2070502


People also ask

What is struct elixir?

In Elixir, Structs are maps with reduced functionality, compile-time checks, and default values. Reduced functionality means that structs cannot use protocols defined for maps like Enum , but can use functions from the Map module.


1 Answers

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"} 
like image 119
Juliano Avatar answered Sep 21 '22 02:09

Juliano