How to group by Graphql query result

Viewed 3716

I have a following GraphQL query

query {
  Result: querydata {
    name
    code
    description
  }
}

that returns me the following data

{
  "data": {
    "Result": [
      {
        "name": "Class1",
        "code": "ST1",
        "description": "Value"
      },
      {
        "name": "Class1",
        "code": "ST2",
        "description": "Value"
      },
      {
        "name": "Class2",
        "code": "FS1",
        "description": "Value"
      },
      {
        "name": "Class2",
        "code": "FS2",
        "description": "Value"
      }
    ]
  }
}

In this data, I have a name field that either be "Class1" or "Class2". I wan't to group this data in a way that I can have Class1 and Class2 data separated. Is there any way of doing this. I could have achieved this by running 2 separate queries by providing a name filter but lets say I don't have that option.

I want to transform the result as follow

{
  "data": {
    "Result": [
      "Class1": [
          {
            "code": "ST1",
            "description": "Value"
          },
          {
            "code": "ST2",
            "description": "Value"
          }
      ]

      "Class2": [
          {
            "code": "FS1",
            "description": "Value"
          },
          {
            "code": "FS2",
            "description": "Value"
          }
      ]
    ]
  }
}
1 Answers

What you are describing is something that should either happen on the client side or allow your query type to receive a name option that you use to return the propper class, then the query below would work for what you are needing assuming it was able to lookup the name of the querydata

query {
  Class1: querydata(name: "Class1") {
    code
    description
  }
  Class2: querydata(name: "Class2") {
    code
    description
  }
}
Related