Fill struct with values from list

Hi All,
Is it possible apply values from list to struct directly?

I’ve tried something like this:

#person.ex
defmodule Hello.Person do
  use Ecto.Schema

  schema "people" do
    field(:name, :string)
    field(:surname, :string)
  end
end

#main.ex
atoms = [:name, :surname]
employees = [["Tom", "Smith"], ["John", "Smith"]]

 out =  Enum.map(employees,  fn  ->
            Stream.zip(atoms, employee) |> Enum.into(%Hello.Person{})
          end)

But it doesn’t work ;/

This article should be helpful for you.

The other way to achieve this is to write function like:

defmodule Example do
  def sample(list) do
    map = Enum.into(list, %{})
    struct(Hello.Person, map)
  end
end

and use it instead of Enum.into/2 in your code:

#person.ex
defmodule Hello.Person do
  use Ecto.Schema

  schema "people" do
    field(:name, :string)
    field(:surname, :string)
  end
end

#main.ex
keys = [:name, :surname]
data = [["Tom", "Smith"], ["John", "Smith"]]

out = Enum.map(data, fn values ->
  keys |> Enum.zip(values) |> Example.sample()
end)
2 Likes

The second argument to struct can be a keyword list, so you could simplify a bit

keys = [:name, :surname]
data = [["Tom", "Smith"], ["John", "Smith"]]

out = Enum.map(data, fn values ->
  struct(Hello.Person, Enum.zip(keys, values))
end)
5 Likes