Convert a nested struct into a nested map

  def map_from_struct(%_{__meta__: %{__struct__: _}} = schema) when is_map(schema) do
    schema
    |> Map.from_struct()
    |> from_ecto_struct()
  end

  def map_from_struct(map) when is_map(map) do
    map
    |> Enum.reduce(%{}, fn {key, value}, acc ->
      value =
        case value do
          %_{__meta__: %{__struct__: _}} ->
            from_ecto_struct(value)

          value when is_list(value) ->
            value |> Enum.map(&from_ecto_struct/1)

          _ ->
            value
        end

      Map.put_new(acc, key, value)
    end)
  end

We write a lib of utils around ecto https://github.com/annatel/antl_utils_ecto

one of the functionality is
AntlUtilsEcto.map_from_struct(my_schema)

1 Like