How to flatten an array of arrays of objects using Groq in Sanity.io.
Based on your data structure, the solution to flattening your array of arrays in GROQ is:
'thumbnails': backgroundLists[]->.backgrounds[].assetHere's how this works:
backgroundLists[]- Iterates through your array of references->- Dereferences each reference to get the actual document.backgrounds[]- Accesses thebackgroundsarray field within each document and iterates through it.asset- Extracts the asset object from each image
The key insight is that GROQ automatically flattens nested arrays when you chain array projections. Each [] operator iterates and flattens one level, so when you chain them like []->.someField[], GROQ effectively flattens multiple levels of nesting into a single flat array.
Based on the schema you're working with (an array of references to documents, where each document has a backgrounds array of images), the -> dereference operator is essential. It follows the reference to get the actual document content, then you can access the nested backgrounds array.
If your schema looks like this:
{
title: 'Background list',
name: 'backgroundList',
type: 'document',
fields: [
{
title: 'Backgrounds',
name: 'backgrounds',
type: 'array',
of: [{ type: 'image' }]
}
]
}And you have an array field that references these documents, the query above will give you a flat array containing all the asset objects from all referenced background lists.
Important distinction: The -> operator is specifically for dereferencing - following references to other documents. This is different from just accessing nested arrays. In your case, since backgroundLists is an array of references (not direct nested arrays), you need the dereference operator to access the content of those referenced documents before you can flatten their internal arrays.
This pattern of chaining [] operators with -> is a common GROQ technique for flattening data structures that involve both references and nested arrays.
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.