How AI is powering better personalization in e-commerce [with Vercel]. Sign up now

GROQ: Flatten nested array and extract specific property (usedTime) from tasks

10 repliesLast updated: Nov 29, 2025

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?
🙂
AI Update

Based on your query structure, you're dealing with nested arrays and trying to flatten them while extracting a specific property. The key issue is that you need to properly flatten the nested tasks[].tasks[] structure and then project the usedTime property.

Here's how to achieve what you're after:

*[_type == "internalCustomers" && 'myMail@mail.com' in users[]->email]{
  "totalHours": tasks[].tasks[].usedTime
}

This syntax tasks[].tasks[].usedTime will:

The double array projection ([][]) handles the flattening for you - GROQ automatically flattens nested arrays when you chain array projections like this, as explained in the pipeline components documentation.

Filtering out null values

If you want GROQ to omit null/undefined values (which it sounds like you do), you can add a filter using the defined() function:

*[_type == "internalCustomers" && 'myMail@mail.com' in users[]->email]{
  "totalHours": tasks[].tasks[defined(usedTime)].usedTime
}

This filters the inner tasks array to only include items where usedTime is defined before extracting the values.

Why your attempts returned null

Looking at your attempts:

The correct syntax for accessing properties in nested arrays is to use [] for each array level, then access the property directly with dot notation. The -> operator is specifically for dereferencing document references, not for property access.

Show original thread
10 replies

Was this answer helpful?

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Related contributions