2

How may I change an object with only its reference in Javascript?

var $obj = { original: true }

var $ref = $obj

// Is it possible here to set $obj to {} with only using $ref?
$ref = {} // This doesn't work

console.log($obj)
// => { original: true }

Example usage:

var $objs = { 
  a: {
    wantsToBeAnEmptyObject: true
  },
  b: {
    wantsToBeAnEmptyObject: true
  }
}

_.forOwn($objs, (val) => {
  val = {}
})

Can anyone help me with this problem?

2 Answers 2

3

Is it possible here to set $obj to {} with only using $ref?

It's not possible to change which object $obj refers to using $ref, no. You can change the state of the object they both refer to (adding, updating, or removing properties), but you can't change which object $obj refers to. (Note that removing properties from an object de-optimizes it on most JavaScript engines, making subsequent property access much slower. It doesn't usually matter, since even when "slower" modern engines are still very, very fast. But...)

The usual solution to that is to have $obj refer to an object with a property that refers to the object you want to be able to replace:

var $obj = {obj: { original: true } };
// --------^^^^^--------------------^
var $ref = $obj;
$ref.obj = { replaced: true };
//  ^^^^
console.log($obj.obj.replaced) // true
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This is probably the best way to proceed
2

You can use the delete keyword to remove keys from an object, which I think would accomplish what you're looking for. In your example something like

Object.keys($ref).forEach(key=>delete $ref[key])

would do the trick

4 Comments

Bit of a leap, but that could be what the OP wants (although it's not really what they asked).
I'd say it's exactly what OP asked for. It's a way of changing an object using only a reference to that object. Maybe I'm misunderstanding the question though.
Well, again, it may be, they may not have asked quite what they want. ref = {} // This doesn't work is pretty clearly replacing something with a new object, not just deleting properties from the existing one.
Thank you. I've been having this same problem in many shapes and sizes, so it's useful to know several tricks to overcome it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.