How to create an array of objects for ticket prices in an event schema.

3 replies
Last updated: Sep 15, 2023
Im attempting to add a set of prices to an event schema. They will always be the same, but may not all be needed for each event. Is it possible to create an array where i can add items with a title and value without it having to be a reference to a different document?
AI Update

Yes, absolutely! You can create an array of inline objects without needing to reference separate documents. This is a common pattern in Sanity for exactly your use case - having a reusable structure (like price tiers) that you can selectively add to each event.

Here's how to set it up in your event schema:

defineField({
  name: 'prices',
  title: 'Prices',
  type: 'array',
  of: [
    defineArrayMember({
      name: 'priceOption',
      type: 'object',
      fields: [
        defineField({
          name: 'title',
          type: 'string',
          title: 'Price Title',
          description: 'e.g., "Early Bird", "General Admission", "VIP"'
        }),
        defineField({
          name: 'value',
          type: 'number',
          title: 'Price Value'
        })
      ],
      preview: {
        select: {
          title: 'title',
          value: 'value'
        },
        prepare({ title, value }) {
          return {
            title: title,
            subtitle: `$${value}`
          }
        }
      }
    })
  ]
})

This creates an array field with inline object members. Each price item will have its own title and value fields, and they'll be stored directly in the event document - no separate document types or references needed.

The preview configuration makes it nice to work with in the Studio by showing the title and formatted price. For each event, editors can add only the price options they need from the "Add item" menu, and they can reorder them via drag-and-drop.

The key here is using type: 'object' inside the defineArrayMember - this creates an inline object structure rather than a reference to another document.

Sounds like an array of objects :)
Would this be the correct syntax then?

defineField({
        title: 'Ticket Prices',
        name: 'ticketprices',
        type: 'object',
        fields: [
          {name: 'studentprices', type: 'number', title: 'student Price'},
          {name: 'normalprices', type: 'nubmer', title: 'Normal Price'},
        ]
      }),
Yup, just lob that into this:

defineField({
 type:"array",
 name : "prices",
 of: [//your code]
})

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?