Go Behind the Experience to see how Tecovas brings the West to life with Sanity 🤠 July 18th

Create a copy of an object and change a key-value pair

By Saskia Bobinska

Sometimes you need to change only one key-value-pair in your data, this is how you can do it in 2 lines

Fast way to do so

/** create a copy of the originalDocumentData object 
 * while removing the existing `_id` (which will be the published one).
 * 
  * You can add more values you want to remove in one line of code.
*/
 const draftDoc = (({_id, ...objectValues}) => objectValues)(originalDocumentData)
      
/** Extend the `newDoc` object with a draft `_id`  
*/
 draftDoc['_id'] = 'drafts.' + originalDocumentData?._id

Another way to do so in more lines

/** Another way would be using this logic, 
 * but you would then need to add further lines to delete every other value. 
*/
 const newDocument = {...doc, ...{_id: newDocId, _type: NEW_TYPE}}
 delete newDocument.incomingReferences
 delete newDocument._rev

Lets assume you have a immutable value (for example _id or _type) you need to change for a couple of different types. Immutable values cannot be patched, so you would need to copy the data without the value you want to change and then redefine it, before createOrReplace the new document.

Maybe you need to unpublish a bunch of documents with different data structures or need to change the _type of a couple of types, which means you would have to change only one part (_id or _type) of the object, without touching the other values.
I found this easy way to do so, and thought someone might find it useful too.

FYI: To change immutable values you can of course use better routes (Migration of typesUnpublishing via Document Action), I just needed an example. And sometimes you need a bespoke solution outside of the 2 examples.

For more information on how to work with objects in Javascript/Typescript, see the Mozilla documentation on objects.

Contributor

Other schemas by author