Sheharyar
Sheharyar

Reputation: 75820

Load values into a Struct from a Map in Elixir

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) }

Upvotes: 8

Views: 4827

Answers (1)

Sheharyar
Sheharyar

Reputation: 75820

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: "*********"}

Note: Map.merge/2 cannot handle enforced keys on structs, so it is not recommended for structs

Upvotes: 20

Related Questions