Syntax for Outputting an Array in GROQ

5 replies
Last updated: Feb 2, 2023
When I use a variable that is an array in groq it seems to output a comma seperated string, instead of an array of strings. Whats the correct syntax for this to be an array?
*[_type == 'portfolio' && _id in ['${ids}'] ]{
This is what its currently printing

*[_type == 'portfolio' && _id in ['416927ba-3c52-40f9-b3eb-c41d18010b29,c34dedda-4325-49c6-8270-08084c867213,aff6dd72-add1-44e0-bc14-784a8f5fba98,bb15831f-c31f-4020-bf20-157d97ab278f']]{
AI Update

The issue is that you're using JavaScript template literal interpolation ('${ids}') which converts your array to a comma-separated string. Instead, you should pass the array as a GROQ parameter.

The correct syntax is:

*[_type == 'portfolio' && _id in $ids]

Then pass your array as a parameter when executing the query:

const ids = [
  '416927ba-3c52-40f9-b3eb-c41d18010b29',
  'c34dedda-4325-49c6-8270-08084c867213',
  'aff6dd72-add1-44e0-bc14-784a8f5fba98',
  'bb15831f-c31f-4020-bf20-157d97ab278f'
]

const result = await sanityClient.fetch(
  `*[_type == 'portfolio' && _id in $ids]`,
  { ids }
)

Why this happens:

When you use '${ids}' in a template literal, JavaScript converts the array to a string using .toString(), which joins array elements with commas. This creates a single string value instead of an array, resulting in the malformed query you're seeing.

Why parameters are better:

Using GROQ parameters with the $ syntax:

  • Maintains proper data types (your array stays an array)
  • Prevents GROQ injection vulnerabilities
  • Automatically handles proper escaping
  • Makes your queries cleaner and more maintainable

The Sanity client handles all the encoding automatically when you pass parameters as the second argument to fetch(), so you don't need to worry about converting the array yourself.

join the ids with
","
as separators
*[_type == 'portfolio' && _id in ['${ids.join("','")}'] ]{
You’ll want to remove the single quotes around your ids variable. You’re currently explicitly making a string.
Thanks
user B
that worked perfectly
Not entirely sure why a join worked if it was already outputting comma separated string... but that seems to be working.
In your example
['${ids}']
becomes ``['a,b,c,d']``, which is a single id. In my example you counter the opening and closing
'
by adding multiple
'
between the items, creating
['a','b','c','d']
.

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?