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
S
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
Data looks like:
I tried using the JS version of the Sanity Client:
Semi-pseudo code:
Not sure how to access each element of the ‘*contentArray’* array in the
I tried to loop through each contentArray element but this didn’t work:
or setting to empty array:
Thanks in advance for any suggestions
set()the
projectskey 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" }
Semi-pseudo code:
sanityClient .patch('_id') .unset(['contentArray.projects']) .commit()
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() })
.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
Unset will remove the
projectsarrays inside of
contentArrayitems, 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) })
projectsarrays from the JSON, as is customary in Sanity when an array is empty.
Apr 6, 2022, 1:47 AM
S
thanks
user A
(as usual!) … worked like a charm and I learned about JSONMatch to target items in patches like set(), unset(), etcApr 6, 2022, 7:35 AM
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.