8

If I have an object like this:

obj = {a:{aa:1}, b:2};

and I want to create a shortcut variable (pointer to obj.a.aa) x like this:

x = obj.a.aa;

and then I want to assign the value 3 to obj.a.aa using x like this:

x = 3;  // I would like for obj.a.aa to now equal 3
console.log(obj.a.aa); // 1  (I want 3)

How can I set x up to result in the value 3 going into obj.a.aa?

I understand that obj.a.aa is a primitive, but how can I define a variable that points to it which I can then use to assign a value to the property?

2

3 Answers 3

9

You cannot use x = value as that will not keep any references, just a copy. You would have to reference the parent branch in order to do so:

x = obj.a;

then set the value:

x.aa = 3;
Sign up to request clarification or add additional context in comments.

2 Comments

So I have to stay one level higher than the property value by always referencing the direct parent object?
@ChrisG. For value types yes.
3

Or, use a function:

var set_x = function(val){
  obj.a.aa = val;
}

Comments

0

Of course you can't - you're not trying to modify the reference that is the name of the object property, you're trying to modify the object. To modify the object, you'll need a reference to the object.

That being said there's probably a creative way to do this. Create a function that takes as a constructor the object, and give the function a customer = setter or method that modifies the object reference. Something like this might work.

Comments

Your Answer

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