elixir

What's a good solution to drop nil value in a struct for Elixir?


For example, I have a struct

post = %Post{title: "Title", desc: nil}

And I want to get

%{title: "Title"}

My solution is like

post
  |> Map.delete(:__struct__) # change the struct to a Map
  |> Enum.filter(fn {_, v} -> v end)
  |> Enum.into(%{})

It works, but is there a better one?

Update:

I feel it annoying transforming from Struct to Map, then Enum, then Map again. Is there a concise way?


Solution

  • Instead of doing

    post
      |> Map.delete(:__struct__) # change the struct to a Map
      |> Enum.filter(fn {_, v} -> v end)
      |> Enum.into(%{})
    

    You can do

    post
      |> Map.from_struct
      |> Enum.filter(fn {_, v} -> v != nil end)
      |> Enum.into(%{})
    

    It's just slightly cleaner than deleting the __struct__ key manually.