graphql

How to filter list objects by field value in GraphQL?


Say I have the following json data:

"data": {
    "continents": [
        {
            "code": "AF",
            "name": "Africa",
        },
        {
            "code": "EU",
            "name": "Europe"
        },
        // ...
    ]
}

What would be the correct GraphQL query to fetch a list item with: code : "AF"? In other words, how to produce the following result:

"data": {
    "code": "AF",
    "name": "Africa"
}

So far, I have:

query {
  continents {
    code
    name
  }
}

but that simply returns the full array.

I've been running my examples on: https://lucasconstantino.github.io/graphiql-online/


Solution

  • For this current example you can just do

    query {
      continents(filter: {code: {eq: "AF"}}) {
        name
      }
    }
    

    I'd suggest to review the documentation regarding arguments since they explain it quite well.