Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Create struct based on dynamic variable

Tags:

struct

elixir

Is it possible to create a struct based on a dynamically passed variable ?

Something like that:

  def create_map_list(list, atom, struct) do
    Enum.filter(list, &Map.has_key?(&1, atom))
    |> Enum.map(
      &%struct{
        id: &1.new_agent.id,
        name: &1.new_agent.name,
        primary_skillset: &1.new_agent.primary_skillset,
        secondary_skillset: &1.new_agent.secondary_skillset
      }
    )

end

like image 911
Heron Rossi Avatar asked Jun 04 '18 15:06

Heron Rossi


Video Answer


1 Answers

Yes, using Kernel.struct/2:

iex(1)> defmodule A do
...(1)>   defstruct [:x]
...(1)> end
iex(2)> [1, 2, 3] |> Enum.map(&struct(A, x: &1))
[%A{x: 1}, %A{x: 2}, %A{x: 3}]

In your case, that would be:

&struct(struct,
  id: &1.new_agent.id,
  name: &1.new_agent.name,
  primary_skillset: &1.new_agent.primary_skillset,
  secondary_skillset: &1.new_agent.secondary_skillset
)
like image 197
Dogbert Avatar answered Oct 12 '22 10:10

Dogbert