Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 761
Tony Han Avatar asked Mar 30 '15 16:03

Tony Han


1 Answers

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.

like image 96
hahuang65 Avatar answered Sep 18 '22 09:09

hahuang65