
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeI can see you're trying to filter variant references based on a selected product within an array structure. This is a common challenge when working with nested arrays in Sanity Studio.
The key issue is that when you're in the variants array, you need to access the parent product field to filter which variants should be available. The tricky part is that parent gives you the variants array itself, so you need to traverse up through the document to find the product reference.
Based on the conditional fields documentation and solutions from the Sanity community, here's how to solve this:
defineField({
name: 'products',
title: 'Products',
type: 'array',
of: [
defineArrayMember({
name: 'productWithSelectedVariants',
title: 'Product with selected variants',
type: 'object',
fields: [
defineField({
name: 'product',
title: 'Product',
type: 'reference',
to: [{ type: 'product' }],
weak: true,
}),
defineField({
name: 'variants',
title: 'Variants',
type: 'array',
of: [
defineArrayMember({
name: 'variant',
title: 'Variant',
type: 'reference',
weak: true,
to: [{ type: 'productVariant' }],
options: {
filter: ({ parent, document }) => {
// Find the product object that contains this variants array
const productObj = document.products?.find(
(p) => p.variants === parent
)
// Get the product reference ID
const productID = productObj?.product?._ref
if (!productID) {
return {
filter: '_type == "productVariant"',
params: {}
}
}
return {
filter: '_type == "productVariant" && references($productID)',
params: {
productID,
},
}
},
},
}),
],
}),
],
}),
],
})How this works:
filter callback receives parent (the variants array) and document (the entire document)document.products to find which product object contains this specific variants array by comparing p.variants === parentproduct._ref to get the product IDreferences() function to filter variants that reference this specific productImportant notes:
parent parameter in the filter callback refers to the variants array itself, not the parent object containing itproductVariant documents have a reference field pointing back to their parent product for the references() filter to work properlyIf your variant documents don't have a reference back to the product, you'll need to adjust the GROQ filter to match based on other fields like a productId string field or similar identifier that connects variants to their products.
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store