GROQ query for nested :items attributes in path
Based on the documentation I found, when working with nested arrays in GROQ queries where the path is something like root[":items"].child[":items"], you can use GROQ's array projection and dot notation to traverse this structure.
Basic Array Traversal
In GROQ, the [] operator projects over arrays. For nested arrays, you can chain them together:
*[_type == "yourType"]{
root[]{
child[]{
// your fields here
}
}
}This will iterate over all items in the root array, and for each of those, iterate over all items in the child array.
Accessing Specific Indices
If you need to access specific array elements, you can use bracket notation with indices:
*[_type == "yourType"].root[0].child[2]According to the Sanity documentation on patches, which uses JSONMatch syntax (similar to GROQ), you can:
- Use
array[0]for the first element - Use
array[-1]for the last element - Use
array[2:]for slicing from index 2 onwards
Filtering Within Nested Arrays
You can also add filters at each level:
*[_type == "yourType"]{
root[_type == "specificType"]{
child[active == true]{
fieldName
}
}
}Flattening Nested Arrays
If you want to flatten the nested structure, you can use the [] operator multiple times:
*[_type == "yourType"].root[].child[]This will give you a flat array of all child items from all root items.
The key difference between [] and [index] is:
[]- projects over all elements (iteration)[index]- accesses a specific element by position[condition]- filters elements based on a condition
For more complex queries, you can refer to the GROQ documentation and the query cheat sheet.
Show original thread38 replies
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.