If I understand your question correctly, the answer is probably "not without doing really weird stuff." What I believe you are asking is this. Given:
const obj = {
x: {
y: {
z: 'test'
}
}
}
you want to store obj.x
(equivalently, obj['x']
) into a variable, in such a way that assigning to that variable will actually mutate the x
field of object obj
. Now you cannot do that. Once you make the binding:
let root = obj.x
Then reassigning root
will NOT change obj
at all: root
is a distinct variable from obj
. Draw a picture, it will help. However, root
is essentially a pointer to obj.x
so if you did:
root.y = 'test 2'
than this does mutate obj.x.y
.
But, note you cannot assign obj.x
to a variable and then use that variable to mutate the x
field of obj
. You can only mutate fields WITHIN obj.x
. JavaScript does not have the ability to alias things (or make lvalues) like C++, for instance.
If you really want to update the x
property of obj
then you should put ONLY the string x
into a variable like this:
root = 'x'
then you can do:
obj[root] = 'a new value for obj.x'
and this will mutate obj.x
. But remember, you cannot first evaluate obj.x
and then use that result to mutate obj.x
. Well, I mean, not without doing some really nasty stuff like this:
root = 'obj.x';
eval(`${root} = 'a new value for obj.x';`);
But don't.
By the way, if obj
was also a variable, then you could do this:
receiver = obj;
prop = 'x';
Reflect.set(receiver, prop, 'the new value')
Hopefully I guessed what you were trying to do. At any rate, maybe this answer will give some ideas.