How to mutate an array field in Sanity document?

26 replies
Last updated: Jan 28, 2026
Hi everyone! What's the correct way to make a mutation for this type of data in my document?
{
  title: 'Contact options',
  name: 'options',
  type: 'array',
  of: [{ title: 'Option', type: 'option' }]
}

AI Update

For your array field, you have a few different approaches depending on what you want to do with the data. Here's how to handle mutations for that array type:

Using the JavaScript Client

If you're working with the Sanity JavaScript client, here's how to mutate your options array:

Adding items to the array

import { v4 as uuidv4 } from 'uuid';

client
  .patch('document-id')
  .setIfMissing({options: []}) // Ensure the array exists
  .insert('after', 'options[-1]', [
    {
      _type: 'option',
      _key: uuidv4(), // Generate unique key
      // ... your option fields
    }
  ])
  .commit()

Setting the entire array

client
  .patch('document-id')
  .set({
    options: [
      {
        _type: 'option',
        _key: uuidv4(),
        // ... your option fields
      }
    ]
  })
  .commit()

Using the HTTP API directly

If you're using the Mutation API directly:

{
  "mutations": [
    {
      "patch": {
        "id": "document-id",
        "insert": {
          "after": "options[-1]",
          "items": [
            {
              "_type": "option",
              "_key": "unique-key-here",
              // ... your option fields
            }
          ]
        }
      }
    }
  ]
}

Important: The _key property

Every object in a Sanity array must have a unique _key property. This is crucial for:

  • Real-time collaborative editing
  • Proper rendering in Studio
  • Identifying specific items for updates

Use a UUID library to generate these keys programmatically. The Studio generates them automatically, but when using the API directly, you need to provide them yourself.

Other useful array operations

  • Append: Use "after": "options[-1]"
  • Prepend: Use "before": "options[0]"
  • Replace: Use "replace": "options[2:]" to replace from index 2 onwards

Check out the patches documentation for more advanced operations!

Show original thread
26 replies

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?