How to filter Sanity array to return single object by ID, not empty objects
I have a VanguardsList document containing a Vanguards array of vanguard object .
I set an id for every vanguard (which I use as a slug for my dynamic routing in NextJs).
inside NextJs getStaticProps(), I only want to fetch the vanguard object matching the id (the current slug of the page..).
Currently, I am able to filter de data but I still get an array containing multiples objects (all empty except the one with the right id).
I want to query only the object witht he right id (without the empty ones)
first img is document structure and second is query inside Vision
I understand your issue! You want to filter a nested array within a document to get only the single matching vanguard object by its ID, rather than getting an array with empty objects.
The key is to use GROQ's array filtering with projection to select just the matching object from your Vanguards array. Here are a few approaches:
Option 1: Filter the array and get the first match
*[_type == "VanguardsList"][0] {
"vanguard": Vanguards[id == $slug][0]
}This returns just the matching vanguard object directly.
Option 2: Inline the result (most common for Next.js)
*[_type == "VanguardsList"][0].Vanguards[id == $slug][0]This gives you the single vanguard object directly, which is perfect for getStaticProps().
Option 3: More explicit projection
*[_type == "VanguardsList"][0] {
"vanguard": Vanguards[id == $slug][0] {
id,
// ... other fields you want
}
}In your Next.js getStaticProps():
export async function getStaticProps({ params }) {
const slug = params.slug; // or however you're getting the id
const query = `*[_type == "VanguardsList"][0].Vanguards[id == $slug][0]`;
const vanguard = await client.fetch(query, { slug });
return {
props: {
vanguard
}
};
}The key differences from what you were likely doing:
- Use
[id == $slug]to filter the array to only matching items (where$slugis a parameter you pass to the query) - Use
[0]at the end to get the first (and only) match as an object, not an array - The
.Vanguardssyntax directly accesses the array property
This approach avoids getting an array with empty objects because you're filtering the nested array before the final selection, and [0] returns a single object rather than an array.
If you're still seeing empty objects, make sure:
- The
idfield in your vanguard objects matches exactly (case-sensitive) - You're passing the parameter correctly to your query
- The field name is
Vanguards(capital V) as shown in your structure
Show original thread2 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.