Zesky665
How to iterate over a Presence map?
Hi,
I need to somehow iterate over the entries in the map returned by Presence.list/1. This is what the map looks like on my end.
%{
"user:1" => %{
metas: [
%{initiator: 2, phx_ref: "tL574g0pn6w=", user_id: 1, username: "admin"}
]
},
"user:3" => %{
metas: [
%{initiator: 1, phx_ref: "7Qvfk3qEksE=", user_id: 3, username: "bob"}
]
}
}
What I need is to iterate over all of them and assign each with a initiator based on the order in which they appear in the map (ex: 1,2,3,4).
Marked As Solved
Nicd
It seems I made a mistake, I replaced the whole metas list with the first element in the list. The error is in updated_val = put_in(val[:metas], meta). Instead of just meta there, we should use [meta | tl(val.metas)] so it is a proper list again.
Note that I am assuming it is the first element in the metas list that you need to change. If it’s some other element, this may not work. Which makes me think there is some better API for this than modifying the structures directly.
Also Liked
Nicd
You can iterate a map with Enum.map for example but note that maps are not ordered so it is not guaranteed that you get any specific order for the users.
Example:
iex(1)> Enum.map(%{"a" => 1, "b" => 2}, fn {k, v} -> {k, v + 1} end) |> Enum.into(%{})
%{"a" => 2, "b" => 3}
Nicd
Unsure where you want the initiator value, in the metas list or somewhere else? What do you want a single user map to look like?
Nicd
This kind of sounds like an XY problem (I don’t understand why you need to do this), but here’s something:
updated = for {{user, val}, i} <- Enum.with_index(your_data) do
meta =
hd(val.metas)
|> put_in([:initiator], i + 1)
updated_val = put_in(val[:metas], meta)
{user, updated_val}
end
updated_map = Enum.into(updated, %{})
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









