How to get the structure based on a key value?

Hi there,
I am new to Phoenix and enjoying it so far. While working on a small project, I ran into an issue. I am hoping to get some help here.

I have a map as follows

[
  %User{
    email: "email1@example.com",
    gender: "female",
    username: "bluecat651",
    password: "secret1",
    phone: "(403)-344-8344"
  },
  %User{
    email: "email2@example.com",
    gender: "male",
    username: "bluecat652",
    password: "secret2",
    phone: "(469)-111-8344"
  }
]

I want to get the full map for gender = ‘male’ . What is the best way to do it?

There are a few missing pieces that need to be clarified from your side, but I’ll put a few assumptions.

What you have there is a list of maps.

I’m assuming you are using ecto to query your User schema, in which way the following might work:

users = Repo.get_by!(User, gender: "male")

This will return a list of only male users.

Or, if you want to filter an existing list with mixed genders:

male_users = Enum.filter(all_users, fn u -> u.gender == "male" end)

I hope this helps.

5 Likes

Thank you very much.