Issue with filtering a reference based on a language key in a Slack thread.

2 replies
Last updated: Mar 16, 2024
I would like to filter this reference based on a set language key, I'm not succeeding with the following, can anyone spot the issue?

return {
    filter: `title[_key] == $language`, // not working
    filter: `title[]._key == $language`, // not working
}
AI Update

Looking at your filter syntax, the issue is that you're trying to filter on a localized field structure. When you have a field like title that contains language-keyed objects, you need to filter differently.

Based on your examples, it seems you have a structure like:

title: [
  {_key: "en", value: "English Title"},
  {_key: "es", value: "Spanish Title"}
]

The correct syntax to filter this should be:

return {
  filter: `title[_key == $language]`,
  params: {language: 'en'} // or whatever language you want
}

The key difference is:

  • title[_key == $language] - This filters the array and returns matching elements
  • Your title[_key] syntax doesn't work because you can't extract _key as an array like that
  • Your title[]._key syntax treats it as accessing a property after array expansion, which isn't the right approach for filtering

If you're working with the @sanity/language-filter plugin or a similar localization setup, this pattern should work. Make sure you're also passing the params object with your language value.

If you're using this in a reference field filter in your schema, it would look like:

{
  name: 'myReference',
  type: 'reference',
  to: [{type: 'myDocument'}],
  options: {
    filter: 'title[_key == $language]',
    filterParams: {language: 'en'}
  }
}

For more on Sanity's localization approaches, check out the localization documentation.

Please try
$language in title[]._key
.
Thanks
user A
That works!

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?