Samuel-88

Samuel-88

Create a new map with multiple keys through each iteration of Map.new()

Hello all,

I have a list of structs, and I want to iterate through each element and from each element create a new map with multiple keys.
Like the example bellow:

User.list_users() // Returns a list of User structs
|> Map.new(fn user ->
      {"#{user.first_name} #{user.last_name}",
       %{         
         "id" => user.id,
         "role" => user.role           
       }}
    end)

But what I actually want to return for Phoenix View, is a list with maps like this:

[%{"id" => user.id, "role" => user.role, "name" => user.name}, {"id" => user.id, "role" => user.role, "name" => user.name}, ...]

So this way Phoenix view returns a list of objects like that.
I’m trying to find a solution for this but Map.new() only allows for one key, value pair.
Does anyone know how I could solve this?

Thanks in advance for all the help!

Marked As Solved

stefanluptak

stefanluptak

You’re using Enum.map/2. That takes a list as an input and returns a list with the same number of elements as output.
Each element of the output is created by the mapper function (the 2nd argument of the Enum.map).

It’s up to me what I will do with that element.

I can ignore the input completely:

Enum.map([:a, :b, :c], fn _ignoring_element -> :x end)
# [:x, :x, :x]`

I can convert each element to a different “type”:

Enum.map([:a, :b, :c], fn element -> Atom.to_string(element) end)
# ["a", "b", "c"]

And in your case, you can do something similar:

Enum.map(users_list, fn user_struct ->
  %{
    "a" => user_struct.id,
    "b" => user_struct.name,
    "c" => DateTime.utc_now(),
    "d" => (1 + 2 * 3)
  }
end)

Also Liked

stefanluptak

stefanluptak

Hi Samuel,

assuming your input is something like this:

defmodule User do
  defstruct [:id, :name, :role, :age]
end
users_list = [
  %User{id: 1, name: "Alice", role: "user", age: 20},
  %User{id: 2, name: "Bob", role: "admin", age: 30},
  %User{id: 3, name: "John", role: "editor", age: 40}
]

you can do this:

Enum.map(users_list, fn user_struct ->
  Map.take(user_struct, [:id, :name])
end)

with this as an output:

[%{id: 1, name: "Alice"}, %{id: 2, name: "Bob"}, %{id: 3, name: "John"}]

or shorter version:

Enum.map(users_list, &Map.take(&1, [:id, :name]))

with this as an output:

[%{id: 1, name: "Alice"}, %{id: 2, name: "Bob"}, %{id: 3, name: "John"}]

You will have to adjust that code a bit, based on your needs, of course.

I am not sure, if the keys of the map have to be strings or can be atoms like in my example. If those have to be strings, I would use something like this approach:

Enum.map(users_list, fn user_struct ->
  user_struct
  |> Map.take([:id, :name])
  |> Map.new(fn {key, value} ->
    {Atom.to_string(key), value}
  end)
end)

But I feel like this is an XYproblem

You should be able to provide your structs to your views, and convert them to maps there with only the keys you want. Did you try that approach?

Samuel-88

Samuel-88

Thanks again for your answer Stefan.

You perfectly solved my problem.
To be honest I forgot you could use structs with Enum.map
It’s very easy to use and the code becomes very readable.

Where Next?

Popular in Questions Top

Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New

Other popular topics Top

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New

We're in Beta

About us Mission Statement