Modifying a string value via a callback in JavaScript

8 replies
Last updated: Jun 16, 2020
Hi! I'm struggling with some javascript. Can someone who knows more about JS confirm the following?
I'm trying to modify the value of a string via a callback, but I think my efforts are futile.


var object = {
  item: {
    content: ""
  },
  collection: []
}

function preprocess(callback) {
// ...
}

preprocess(({ collection, content }) => {
    content = "new content"
    collection = ["new-item-1", "new-item-2", "new-item3"];
});

console.log(object.item.content)
// => "new content"
Is there a way to make this work?
AI Update

This question is about general JavaScript concepts (passing values vs references, destructuring, and callbacks) and isn't related to Sanity. You'll get better help posting this in a JavaScript-focused community like:

If you have questions about using JavaScript with Sanity — like writing GROQ queries, creating custom input components, setting up validation functions, or working with Sanity Functions — I'm happy to help with those!

It looks like you’re not passing in
object
anywhere for it to be modified.
Object would be passed inside the function.
So something like


function preprocess(callback) {
  callback({collection: object.collection, content: object.item.content})
}

This is a simplified example.
I don’t think that will work. You’re expecting
content
to be a “reference” to the
object.content
but when you destructure args likes that you will get a “copy” of the arg (not a reference).
If you modify that variable you are only modifying your local copy — not the original
see here
object
never gets modified
but if you handle the whole
object
in your function you can modify
object
(because you haven’t destructured it in the function signature
Hey, thanks. I understand now that I have to pass the object through. This clarifies my thinking that you can only modify an object that is passed through a callback.
For my use case I cannot pass the object through, but I have some alternative ideas.

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?