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

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
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
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
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
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement