🎤 Builder Talk: The Story Behind Lady Gaga’s Digital Experience – Register now

How to patch a field of an object in an array using the Sanity JavaScript client

7 replies
Last updated: May 29, 2023
Hey guys !I'm trying to patch a field of an object in an array with the js client, but I don't see how it's possible in a clean way.
Let's says I have something like this :

{
    "_id": 'aFuiYGWUw0SSAvMnYQafry',
    "entries": [
        {
            "_key": "BjDASDLOMkBsqk1tqRecKu"
            ...other keys and values
        },
        {
            "_key": "E0vulMwINU3H9ETBqXnRT7",
            ..oher keys and values
            "subentries": [
                {
                    "data": "saved datas",
                    "_key": "6b8c867d-36b9-4eff-97e0-9fd5be6c6ee4"
                },
                => insert data here
            ]
        }
    ]
}
For now, the only solution I found was to fetch the entire document, edit the result in JS and patch with the full data.
• It is not very clean, and need another request
• I lost some fields value, even if I checked that all data was there
Any better idea ?
May 24, 2023, 10:22 PM
Hi
user Q
, just I'm not sure yet what you're looking for...
Have a look at the first example on this doc page for patches -- it's not requesting any other records to do the `patch`; you'd just send this mutation query through the client, no?
https://www.sanity.io/docs/http-patches
You might need another query to get the values to fill in, but isn't that natural?

Clean if needed, for me anyway, but it could well be I'm missing what's really your concern here, so far....

Best, (Removed Name)
May 25, 2023, 3:45 AM
Let’s say I want to replace the value of a field in the second object of an array. I don’t see how I can use the index or the key there to updte a specific target without touching the others
May 25, 2023, 7:21 AM
Well, a patch lets you focus on just one object and one field in it, if you want, doesn't it?
I'm viewing this that you are targeting that object in the patch, not the array holding it, which shouldn't need touching?
May 25, 2023, 7:26 AM
hm, I think I got it :I was looking for a condition like this :
{ "set": { "body[_type==\"cta\"].text": "Do the thing!" } }


{
  "mutations": [
    {
      "patch": {
        "id": "aFuiYGWUw0SSAvMnYQafry",
        "set": {
          "entries"[_key==\"E0vulMwINU3H9ETBqXnRT7\"] : {
            "insert": {
              "after": "subentries[-1]",
              "items": ["=> insert data here"]
            }
          }
        }
      }
    }
  ]
}
I will try this later, thanks
user Q
May 25, 2023, 8:11 AM
Most welcome, (Removed Name), and glad you saw into it :)
May 25, 2023, 8:12 AM
Hey ! just to confirm I was on the right path, this works like a charm (js client)
writeClient.patch(<documentID>)
        .setIfMissing({
            [`entries[_key==\"${entryId}\"].subentries`]: []
        })
        .append(`entries[_key==\"${entryId}\"].subentries`, [{
            _key: uuid(),
            ...=> data here
        }])
        .commit()
May 28, 2023, 11:01 PM
Good man :) Looks like you covered the angles nicely, and this will be good for others to find. Take care, (Removed Name), (Removed Name) (we're having a long weekend over here, so things will be quiet)
May 29, 2023, 4:01 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.

Was this answer helpful?

Related answers

Get more help in the community Slack

TopicCategoriesFeaturedRepliesLast Updated
Filtering out duplicate slugs after a large data importSep 8, 2020
Modifying a string value via a callback in JavaScriptJun 16, 2020
How to perform a "publish" through the API/JavaScript client in Sanity.ioJul 21, 2020
I’m experiencing an error when trying to deploy `sanity graphql deploy` and getting this error point towards a node_module ```import...Jan 16, 2021
Gatsby site crashing with cryptic error, resolved by adjusting resolveReferences depthAug 18, 2020
Browsing raw data and wiping all data in a Sanity instance discussed.Apr 28, 2020
Updating object properties in an array on a document with the Sanity clientMar 17, 2021
Discussing Sanity and Shopify integration, speed optimization, and alternativesSep 9, 2021
Making GROQ params optional in Next.js frontend API endpoint queryJan 19, 2022
Error in React/Sanity tutorial code, resolved with missing comma in querySep 29, 2021

Related contributions

Turbo Start Sanity
- Template

The battle-tested Sanity template that powers Roboto Studio's websites

Go to Turbo Start Sanity

Schema UI - Next.js Sanity Starter
- Template

A Next.js starter template with Next.js 15, Tailwind CSS, shadcn/ui, and Sanity CMS with Live Editing. Get production-ready React components with matching Sanity schemas and queries. Build dynamic pages faster while keeping full control over customization.

Serge Ovcharenko
Go to Schema UI - Next.js Sanity Starter

The Swaddle
- Made with Sanity

A new brand identity to represent a more mature company, to signify The Swaddle’s evolution from publisher to production house, combined with an easier to navigate platform that can surface multiple content types - drawing readers through The Swaddle’s content offering.

Nightjar
Go to The Swaddle