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,
    },
  }
]

event.js

export default {
  name: "Event",
  title: "Event",
  type: "document",
  fields: [
    {
      name: "label",
      title: "Title",
      type: "string"
    }
  ],
  preview: {
    select: {
      title: "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'}
      ]
    }
  ],
  preview: {
    select: {
      title: "name"
    },
  },
};

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 i possible, but for now it is a neat trick.

Contributor