Next.js - How to Filter an Array of Objects for a Specific ID
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
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.