I want to put a check on Permission level "Owner" from enum map

I am getting project permissions access level and accessing it through Enum.map(). I want to put a check if it is "Owner" how do I do that from a map. How do I do that


project_permissions = ProjectPermissions.list_project_permissions()

        Enum.map(project_permissions, fn %{id: id, access_level: access_level} ->
          {access_level, id} |> IO.inspect()
        end)
{"Owner", 1}
{"Moderator", 2}
{"Viewer", 3}

Can you rephrase or provide a more specific example of what you’re asking for?

This is not clear (to me, at least) if you want to select a checkbox in the UI, or confirm if the list contains an item with the permission "Owner"

confirm if the list contains an item with the permission "Owner"

Depending on what you need I will give you few examples …

Let’s start with initial data:

iex> project_permissions = [
  %{access_level: "Owner", id: 1},
  %{access_level: "Moderator", id: 2},
  %{access_level: "Viewer", id: 3}
]
[
  %{access_level: "Owner", id: 1},
  %{access_level: "Moderator", id: 2},
  %{access_level: "Viewer", id: 3}
]

We can simply check if in said project_permissions list are any items with access_level set to Owner:

iex> Enum.any?(project_permissions, & &1.access_level == "Owner")
true

You can also easily filter results by map value:

iex> Enum.filter(project_permissions, & &1.access_level == "Owner")
[%{access_level: "Owner", id: 1}]

Alternatively you can use for with filter:

iex> for %{access_level: access_level, id: id} <- project_permissions, access_level == "Owner", do: {access_level, id}
[{"Owner", 1}]

Helpful resources:

  1. Enum.any?/2
  2. Enum.filter/2
  3. for special form
  4. Comprehensions article at elixir-lang.org
1 Like

It is a similar solution to your other question :slightly_smiling_face:

permissions =
  Enum.map(project_permissions, fn %{id: id, access_level: access_level} ->
    {access_level, id} |> IO.inspect()
  end)

Enum.any?(permissions, fn {permission, _id} -> permission == "Owner" end)
# or
Enum.find(permissions, fn {permission, _id} -> permission == "Owner" end)

A more direct way to find the full ProjectPermission struct in one pass:

Enum.find(project_permissions, fn %{access_level: access_level} -> access_level == "Owner" end)

or instead of pulling a list of all records from the database and finding the one you want, you can more efficiently query the one record you want directly from the database

def get_project_permission_by_access_level(access_level) do
  Repo.get_by(ProjectPermission, access_level: access_level)
end

get_project_permission_by_access_level("Owner")

Now i need to put it in condition and list the project with owner permissions

I will try this one