Let's say I've a map
with some user data:
iex(1)> user_map
#=> %{name: "Some User", email: "[email protected]", password: "*********"}
How can I load this into a %User{}
struct (hopefully using some Rubyish Elixir Magic)?
I've currently tried these but all of them failed. Going through the Structs section on Elixir website.
user_struct = %{ %User{} | user_map }
user_struct = %{ %User{} | Enum.to_list(user_map) }
Found the answer on the elixir-lang-talk
mailing list. We can use the struct/2
method:
struct(User, user_map)
#=> %User{name: "Some User", email: "[email protected]", password: "*********"}
Another way, as mentioned by Dogbert, is to use Map.merge/2
:
Map.merge(%User{}, user_map)
#=> %User{name: "Some User", email: "[email protected]", password: "*********"}
caveat from the comments: Map.merge cannot handle enforced keys on structs
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