πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

Splatt, merge and spread documents and objects with GROQ

By Tarje Lavik

query.js

[
  ...*[_type == "Event"]{
    _id,
    label,
  },
  ...*[defined(activities)].activities[featured == true]{
    _id,
    label,
    # Add some data from the parent
    "concerned": ^{
      _id,
      _type,
      label,
    },
  }
]

person.js

export default {
  name: "Person",
  title: "Person",
  type: "document",
  fields: [
    {
      name: "name",
      title: "Title",
      type: "string"
    },
    {
      name: 'activities',
      title: 'Activities',
      type: 'array',
      of: [
        {type: 'Activity'},
        {type: 'reference', to: {type: 'Event'}}
      ]
    }
  ],
  preview: {
    select: {
      title: "name"
    },
  },
};

event.js

export default {
  name: "Event",
  title: "Event",
  type: "document",
  fields: [
    {
      name: "label",
      title: "Title",
      type: "string"
    }
  ],
  preview: {
    select: {
      title: "label"
    },
  },
};

activity.js

export default {
  name: "Activity",
  title: "Activity",
  type: "object",
  fields: [
    {
      name: "label",
      title: "Title",
      type: "string"
    }
  ],
  preview: {
    select: {
      title: "label"
    },
  },
};

I found myself in a situation where i sometimes create Event documents to be able to reference the event elsewhere, but more often have Activity as an object for simple inline editing. This GROQ query will merge / spread / splatt it all together!

I use this to create a timeline of all the activities and events in the frontend.

NB! Might not be necessary when inline document creation is possible, but for now it is a neat trick.

NB! This does not work after an update, on any API version.

Contributor