Watch a live product demo πŸ‘€ See how Sanity powers richer commerce experiences

How to use GROQ to Write Loops

10 replies
Last updated: Jun 29, 2021
I'm trying to use GROQ to save me writing some loops in the front end.
I have an array of tasks, in this array there is a property named "usedTime" indicating how long has been spent on a task, only some of the tasks have this value.

The result I'm after is one array (one dimentional) containing the usedTime data, I can handle null values in my front end but if sanity supports omitting them that would be awesome

Attached is the result of the query

*[_type == "internalCustomers" &amp;&amp; '<mailto:myMail@mail.com|myMail@mail.com>' in users[]-&gt;email]{
  "totalHours": tasks[].tasks[], 
}
I know my naming work needs improving
πŸ˜‰
I've tried several methods

  "totalHours": tasks[].tasks-&gt;usedTime, 
  "totalHours": tasks[].tasks[]-&gt;usedTime, 
  "totalHours": tasks[].tasks[]-&gt;.usedTime, 
  "totalHours": tasks[].tasks.usedTime, 
All my attempts return "null"
Any idea on how I can achive this?
πŸ™‚
Jun 29, 2021, 4:33 PM
I’m wondering if there might be another array to include in your query, given the double-nesting after
totalHours
in your third array item.
Schema:

export default {
  name: 'andreas',
  type: 'document',
  fields: [
    {
      name: 'tasks',
      type: 'array',
      of: [
        {
          name: 'firstObj',
          type: 'object',
          fields: [
            {
              name: 'tasks',
              type: 'array',
              of: [
                {
                  name: 'secondObj',
                  type: 'object',
                  fields: [
                    {
                      name: 'tasks',
                      type: 'array',
                      of: [
                        {
                          name: 'thirdObj',
                          type: 'object',
                          fields: [
                            {
                              name: 'usedTime',
                              type: 'number'
                            },
                          ],
                        },
                      ],
                    },
                  ],
                },
              ]
            }
          ]
        }
      ]
    }
  ]
}
GROQ query:

*[_type == 'andreas'] {
  'totalHours': tasks[].tasks[].tasks[].usedTime
}
Returns:

"result": [
  0: {
    "totalHours": [
      0: 34
    ]
  }
]
Jun 29, 2021, 7:06 PM
As for removing null values, I believe you could try
[count(totalHours) &gt; 0]
at the end of your query. In my example above, it came after the
}
at the end of the projection.

*[_type == 'andreas'] {
  'totalHours': tasks[].tasks[].tasks[].usedTime
}[count(totalHours) &gt; 0]
Jun 29, 2021, 7:09 PM
Hey Geoff, yes it seems to be another arrayed hidden in here. Can't really see why
Your suggestion makes sense, but does not work. I can't see a name for the additional array either

Results of

*[_type == "internalCustomers" &amp;&amp; '<mailto:andreas.jacobsen@inklud.no|andreas.jacobsen@inklud.no>' in users[]-&gt;email]{  
  'totalHours': tasks[].tasks[].tasks[]
}
is null

If I remove the last task-attribute I get this response

https://ad47v47a.api.sanity.io/v1/data/query/production?query=*%5B_type%20%3D%3D%20%22in[…]%20%20%27totalHours%27%3A%20tasks%5B%5D.tasks%5B%5D%0A%7D
Jun 29, 2021, 7:22 PM
Hey Geoff, yes it seems to be another arrayed hidden in here. Can't really see why
Your suggestion makes sense, but does not work. I can't see a name for the additional array either

Results of

*[_type == "internalCustomers" &amp;&amp; '<mailto:andreas.jacobsen@inklud.no|andreas.jacobsen@inklud.no>' in users[]-&gt;email]{  
  'totalHours': tasks[].tasks[].tasks[]
}
is null

If I remove the last task-attribute I get this response

https://ad47v47a.api.sanity.io/v1/data/query/production?query=*%5B_type%20%3D%3D%20%22in[…]%20%20%27totalHours%27%3A%20tasks%5B%5D.tasks%5B%5D%0A%7D
Jun 29, 2021, 7:22 PM
you might want to use the new api version btw
Jun 29, 2021, 7:44 PM
Thanks, using v2021-03-25 in my front end, will change to that in studio as well. Same problem with v2021-03-25
Edit: Sorry my mistake, using the newer API I get the result I want
πŸ™‚
Jun 29, 2021, 7:45 PM
Also, this might be the thing you want?
*[_type == "internalCustomers" &amp;&amp; '<mailto:andreas.jacobsen@inklud.no|andreas.jacobsen@inklud.no>' in users[]-&gt;email]{  
  'totalHours': tasks[tasks != null].tasks
}
Jun 29, 2021, 7:49 PM
GROQ is amazingI tried your not null example Knut, but weirdly I get one null value
But this is pretty easy to handle in the front end
Jun 29, 2021, 7:54 PM
Try
*[_type == "internalCustomers" &amp;&amp; '<mailto:andreas.jacobsen@inklud.no|andreas.jacobsen@inklud.no>' in users[]-&gt;email]{  
  'totalHours': tasks[tasks != null].tasks[usedTime != null].usedTime
}[count(totalHours) &gt; 0]

Jun 29, 2021, 7:57 PM
thanks! That worked, I'll remove count because I just remember that count and sum is not the same thing. GROQ just saved me a bunch of loops I'd have to maintain and try to understand again some time in the future πŸ™‚ Should have thought of tasks being able to be null as well
Jun 29, 2021, 8:00 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Related answers

Get more help in the community Slack

TopicCategoriesFeaturedRepliesLast Updated
After adding the subtitle and running this code npm run graphql-deploy It does nothingSep 15, 2020
how to limit a reference to just one entry in Studio reference input side versus the default as-many-entries-as-you-fill-in-an-array...Sep 18, 2020
Is it possible to fetch more than one "_type" using GROQ?Nov 2, 2020
I want to add a view with the Structure builder (S.view.component) where I list similar documents based on the title. What...Sep 23, 2020
Is there a structure builder example where the format of each preview for the document list is modified?Feb 3, 2021
I have an array of references to a country schema type but it always just returns NULL values for meJan 30, 2021
Hi, I need help with a query for getting the url of an image asset. Here is what I've been trying, but I only get the _ref...Dec 1, 2020
Sanity UI looks brilliant :smiley: Is something like the current date picker possible at the moment? I’m not sure if anicon...Dec 21, 2020
Hey everyone. I have been coding and may have potentially accidentally deleted something. Does anyone know how to resolve...Dec 26, 2020
Hello everyone and happy new year :raised_hands::skin-tone-2:, I have a problem with outputting Portable Text :disappointed:...Jan 1, 2021

Related contributions

Clean Next.js + Sanity app
- Template

Official(made by Sanity team)

A clean example of Next.js with embedded Sanity ready for recomposition.

Cody Olsen
Go to Clean Next.js + Sanity app

Blog with Built-in Content Editing
- Template

Official(made by Sanity team)

A Sanity-powered blog with built-in content editing and instant previews.

Go to Blog with Built-in Content Editing