GROQ: Access nested array without intermediate object structure

2 replies
Last updated: Sep 6, 2023
Hi, i want to show only
selected
array, instead I get selected->type->selected[]
'selected': selected->{

type[0]{

selected[]->{...}

}

}
how can I fix it?
AI Update

Looking at your query, the issue is with how you're structuring your projections with the reference operator. When you write:

'selected': selected->{
  type[0]{
    selected[]->{...}
  }
}

You're creating nested objects unnecessarily. The reference operator -> already resolves the reference, and then you're trying to traverse into it with additional projections that create the unwanted structure.

To fix this and get just the selected array directly, you need to flatten your projection. Here are a few solutions depending on what you're trying to achieve:

If selected is a reference to a document that has a type array, and you want the first type's selected array:

'selected': selected->type[0].selected[]->

This chains the operations: dereference selected, access the first item in type, then get the selected array and dereference each item.

If you want to project specific fields from the dereferenced items:

'selected': selected->type[0].selected[]->{
  _id,
  name
  // your specific fields
}

If selected itself is an array of references:

'selected': selected[]->{
  // fields you want
}

The key insight from the reference access operator documentation is that -> resolves the reference and returns the document data. Each time you wrap something in { }, you're creating a new object level in your response.

Your current query creates this structure because of the nested object projections:

  • selected-> creates the first level
  • type[0]{ } creates the second level
  • selected[]-> creates the third level

Remove the intermediate object wrapping (type[0]{ }) and access the path directly with dot notation or array access. The correct pattern for array references is to use []-> directly on the array field without wrapping it in projection objects.

Show original thread
2 replies
Can you share your schema and what data you are trying to extract? Actual and expected results would be helpful as well.
i fixed it by doing
'selected': selected->type[0].selected[]->{

...

}

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.

Was this answer helpful?