🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

How to unset a field in each item of an array in a document using the Sanity Client.

3 replies
Last updated: Apr 6, 2022
Hi, I have a document that contains an array of items and I am hoping to unset a field in each item. More specifically, in the representative data below where the ‘contentArray’ array contains two elements, I want to
set()
the
projects
key to any empty array (or
unset()
, not sure which).
Data looks like:

{
  "_id": "9c780fd3-0e54-40ad-80c8-fd27dc19359f",
  "contentArray": [
    {
      "_key": "3cd487d4bd8c",
      "_type": "sectionProjectsGrid",
      "projects": [
        {
          "_key": "f880b5219313",
          "_ref": "05064724",
          "_type": "student",
          "_weak": true
        },
        {
          "_key": "432d0796461d",
          "_ref": "65e99226-fcc3-47e2-9419-d4095961d4e1",
          "_type": "student",
          "_weak": true
        }
      ]
    },
    {
      "_key": "0d5871d6ce7b",
      "_type": "sectionProjectsGrid",
      "projects": []
    }
  ],
  "title": "Home"
}
I tried using the JS version of the Sanity Client:

Semi-pseudo code:

sanityClient
    .patch('_id')
    .unset(['contentArray.projects'])
    .commit()
Not sure how to access each element of the ‘*contentArray’* array in the
unset()
method
I tried to loop through each contentArray element but this didn’t work:

contentArray.forEach((item, index) => {
    sanityClient
    .patch('_id')
    .unset([``contentArray[${index}].projects``])
    .commit()
})
or setting to empty array:
.set({contentArray[${index}].projects: []})

Thanks in advance for any suggestions
Apr 5, 2022, 11:39 PM
Hi Steve. If you want to unset all the
projects
arrays inside of
contentArray
items, you could use JSONMatch like:

import sanityClient from 'part:@sanity/base/client'

const client = sanityClient.withConfig({ apiVersion: '2022-04-05' })

client
    .patch('9c780fd3-0e54-40ad-80c8-fd27dc19359f')
    .unset(["contentArray[*].projects"])
  .commit()
  .then((res) => {
    console.log(res, ' updated')
  })
  .catch((err) => {
    console.error('Transaction failed: ', err.message)
  })
Unset will remove the
projects
arrays from the JSON, as is customary in Sanity when an array is empty.
Apr 6, 2022, 1:47 AM
thanks
user A
(as usual!) … worked like a charm and I learned about JSONMatch to target items in patches like set(), unset(), etc
Apr 6, 2022, 7:35 AM
Glad that works for you, Steve! 🙌
Apr 6, 2022, 7:06 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?