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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With