jhefreyzz

jhefreyzz

Hi,
Is there an easier way to convert a list of structs to map. Extracting fields from the struct and in the nested struct and make it a map.

The list of struct:

[
  %Kaiwa.Chat.Message{
    __meta__: #Ecto.Schema.Metadata<:loaded, "messages">,
    id: 1,
    inserted_at: ~N[2020-04-03 11:46:24],
    room: #Ecto.Association.NotLoaded<association :room is not loaded>,
    room_id: 1,
    text: "this is a test message",
    updated_at: ~N[2020-04-03 11:46:24],
    user: %Kaiwa.Accounts.User{
      __meta__: #Ecto.Schema.Metadata<:loaded, "users">,
      id: 1,
      inserted_at: ~N[2020-04-02 04:10:00],
      messages: #Ecto.Association.NotLoaded<association :messages is not loaded>,
      name: "Mr Testing",
      password: nil,
      password_hash: "$argon2id$v=19$m=131072,t=8,p=4$26a9JgOy+rmuhjQ7WZD1bg$ZJe55e9UdfrWqm0E4rMnGFG7mA/Wyr7fWdi1f1tZP+8",
      rooms: #Ecto.Association.NotLoaded<association :rooms is not loaded>,
      updated_at: ~N[2020-04-02 04:10:00],
      username: "test" 
    },
    user_id: 1
  }
] 

My attempt:

Enum.map(messages, fn message ->
  user = Map.from_struct(message.user)

  %{
    message_id: message.id,
    text: message.text,
    created_at: message.inserted_at,
    user_id: user.id,
    name: user.name
  }
end)

Expected result:

[
  %{
    created_at: ~N[2020-04-03 11:46:24],
    message_id: 1,
    name: "Mr Testing",
    text: "this is a test message", 
    user_id: 1
  }
]

Is there a better way to achieve the expected result or my attempt is okay?

Marked As Solved

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe
user_map = Map.take(user, [:name, :id, :username])

Also Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

This is going to include a lot of keys you don’t want like __meta__ and password_hash (very bad). If you’re trying to create a JSON response for an API I recommend just explicitly making maps for each of the things you want to expose.

dimitarvp

dimitarvp

I would be more comfortable with something that asserts the shape of the data it receives so I can catch bugs early:

    Enum.map(
      messages,
      fn %{
           id: message_id,
           text: text,
           inserted_at: created_at,
           user: %{id: user_id, name: name}
         } ->
        %{
          message_id: message_id,
          text: text,
          created_at: created_at,
          user_id: user_id,
          name: name
        }
      end
    )

If even one message doesn’t comply with the expected structure you’ll get an appropriate error. Although to be fair, your code would also blow up but IMO in a slightly less intuitive fashion. I’d prefer mine because it also makes intent clearer.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews