Concat json array into one combine list of arrays that have hashes into one array with all the hashes

User View

  def render("index.json", %{users: users}) do
    %{data: users_json(users), included: includes_json(users)}
  end

  defp include_json(user) do
    # %{type: "Hello", id: "WOW"}
    tags1_json(user.tags)
    # %{type: "taggable", id: user.id, name: user.name, relationships: %{tags: %{data: tags_json(user.tags)}}}

  end

  defp includes_json(users) do
    users |> Enum.map(&include_json(&1))
  end
  defp users_json(users) do
    users |> Enum.map(&user_json(&1))
  end

  defp tags_json(tags) do
    tags |> Enum.map(&tag_json(&1))
  end

  defp tags1_json(tags) do
    tags |> Enum.map(&tag1_json(&1))
  end

  defp tag1_json(tags) do
    %{id: tags.id, type: "taggable"}
  end

  defp tag_json(tags) do
    %{type: "taggable", id: tags.id, name: tags.name}
  end
  defp user_json(user) do
    %{type: "User", id: user.id, name: user.name, country: user.country, relationships: %{taggables: %{data: tags_json(user.tags)}}}
  end

User Controller

  def index(conn, _params) do
    users =
    VampTechnical.User
    |> Repo.all()
    |> Repo.preload(tags: :taggables)
    render conn, users: users
  end

json output right now…

{
included: [
[
{
type: "taggable",
id: "a7d41c25-0452-47eb-b400-7237b2ff2c6d"
}
],
[],
[],
[],
[],
[],
[],
[],
[],
[]
],
data: [
{
type: "User",
relationships: {
taggables: {
data: [
{
type: "taggable",
name: "Photo",
id: "a7d41c25-0452-47eb-b400-7237b2ff2c6d"
}
]
}
},
name: "Alberto Giubilini",
id: "042807cc-26e1-4122-9235-23412eacaa79",
country: "Singapore"
},
{},
{},
{},
{},
{},
{},
{},
{},
{}
]
}

What I am trying to acheive

{
included: [
{
type: "taggable",
id: "a7d41c25-0452-47eb-b400-7237b2ff2c6d"
},
{},
{},
{},
{},
{},
{},
{},
{},
{}
],
data: [
{
type: "User",
relationships: {
taggables: {
data: [
{
type: "taggable",
name: "Photo",
id: "a7d41c25-0452-47eb-b400-7237b2ff2c6d"
}
]
}
},
name: "Alberto Giubilini",
id: "042807cc-26e1-4122-9235-23412eacaa79",
country: "Singapore"
},
{},
{},
{},
{},
{},
{},
{},
{},
{}
]
}

Looks like you probably want an Enum.flat_map instead of an Enum.map.

2 Likes