Go Behind the Experience to see how Tecovas brings the West to life with Sanity 🤠 July 18th

Adding custom objects to GROQ query results and sorting them

12 replies
Last updated: Jun 24, 2024
is it possible to add a custom record/object into a query result...I'm building an index of pages for a "resource center" page and at least one of the items that I need in this index lives in a hard-coded Remix route. Currently, I'm doing the sorting in the groq query itself, so I was hoping I could just inject a new item and then use orderBy before sending that to my Remix loader. Otherwise, I'll have to do some array manipulation first before sending it to the client, which isn't the end of the world, but I'm just curious.
Jun 24, 2024, 4:17 PM
I’m not totally certain it’ll work, but I wonder if you can pass the hardcoded value in with a param:
client.fetch('*[_type == '<your-type>']{
  "remixValue": $remixValue,
  //other fields
} | order(remixValue, desc)', { remixValue })
Jun 24, 2024, 4:22 PM
I'm not sure I follow that. Maybe I didn't explain it that well... I want to query for a certain document type. In this case
_type == "resource"
. Then I want to add a new custom "document" to the results as if it were an actual document in the dataset. Then orderBy a common field, such as title. So a regular query might return an array of two resource documents. I want to append a third and then sort them.
Jun 24, 2024, 4:30 PM
One alternative is to just go ahead and create this resource page in the studio, so it has a title and a slug, but I don't want editors to actual edit anything on this particular page. Hence the hard-coded remix route file. I'm just not sure which is better.
Jun 24, 2024, 4:32 PM
If i can't do it in groq, i'll probably remove the orderBy and then append the item in my Remix loader and then do the sorting there before sending it to the client.
Jun 24, 2024, 4:33 PM
Ok, yes I think that’s still possible. This works for me in the default movie db:
  "result": [
    ...*[_type == 'movie'][0...10],
   ] | order(title asc)  

  "someOtherMovies": [{
    title: 'A Title',
  }, { title: 'Another Title'}]
You should be able to inject your data into a query and sort all in one go.
Jun 24, 2024, 5:19 PM
wow. okay. awesome. thank you!
Jun 24, 2024, 5:19 PM
You’re welcome!
Jun 24, 2024, 5:20 PM
Ah, scratch that, it doesn’t look like it’s actually ordering it. I’ll keep looking.
Jun 24, 2024, 5:25 PM
Oh, no wait, scratch that scratch. It is working 🙂
Jun 24, 2024, 5:26 PM
yeah it's working for me 🙂
Jun 24, 2024, 5:27 PM
anything is possible with groq lol
Jun 24, 2024, 5:28 PM
It’s true 🙂
Jun 24, 2024, 5:28 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?