Register now - Learn how Tecovas roped in success with Sanity and Shopify 🤠

How to patch a specific object in an array of objects using the Sanity CLI.

7 replies
Last updated: Nov 24, 2021
How does one go about patching a specific object in an array of objects when using the Sanity CLI? I couldn't seem to find any documentation on this. Only for shallow updates but not for updating nested values in a document.

// Example document
  "_id": "abc123"
  "packages": [
      _key: "def456",
      _type: "package"
      active: false

// Example patch
    // How do I do this?
	.set({ packages[_key=="def456"]: {active: true})
Nov 24, 2021, 3:56 PM
perhaps not 100% the same, but I wanted to modify individual images in an array (We had a custom sort order attribute we needed to update when rearranging images in our iPhone app).The solution in the end was to store the array locally - delete the array in Sanity, and recreate it with the new correct sort order attribute. On each patch update....
Nov 24, 2021, 4:04 PM
Yea, that could be an option actually. Although I'd be interested if there's a way I'm just not seeing of how to set nested properties. I'm also toying with the idea with making the array of objects an array of references to documents instead (for my purposes it could also make sense to convert my objects into standalone documents).
Nov 24, 2021, 4:22 PM
I've been solving this by making
const document = await client.fetch(`*[_id == 'abc123'][0]`)

document.packages.forEach(package => {
  if (package._key !== 'def456') return = true

await client
Nov 24, 2021, 4:30 PM
Also Sanity Mutations API is powerful and might solve this by not using script. In your case, I'm thinking about Adanced use of JSONMatch part.
Nov 24, 2021, 4:32 PM
Hi User. Looks like you’re really close. You could try the following, which will edit the published document so you may want to account for and handle drafts:

  .set({'packages[_key=="def456"].active': true})
Nov 24, 2021, 8:43 PM
That works, I didn't realize how close I was.

const packageKey = `packages[_key=="${payload._key}"].active`

await client
	.set({[packageKey]: true})
For context this code is assuming there is some payload coming into a Netlify function from a QROQ-powered webhook for example
Nov 24, 2021, 10:07 PM
Good suggestions all around, I haven't made much use of the Sanity Mutations API so that'll definitely be something to look into for future use. Thank you all!
Nov 24, 2021, 10:08 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?

Categorized in