I came across this question as I was building a recursive function to drill into objects. Given an object and path (as an Array of strings):
const path = ['path', 'to', 'nestedObj', 'someProp'];
const obj = {
path: {
to: {
nestedObj: {
someProp: 'someValue'
}
}
}
}
I came up with this solution:
function setValueFromPath(object, path, value) {
let nestedObj = object[path[0]];
const nextPath = path.slice(1, path.length);
if(path.length > 1) {
return setValueFromPath(nestedObj, nextPath, value);
}
nestedObj = value;
}
It didn't reassign the value to some prop however. To me this means the last line, in nestedObj = value
, nestedObj
is not holding a reference to the original obj.
So I did some fiddling and tried this:
function setValueFromPath(object, path, value) {
let nestedObj = object[path[0]];
const nextPath = path.slice(1, path.length);
if(path.length > 2) {
return setValueFromPath(nestedObj, nextPath, value);
}
nestedObj[path[1]] = value;
}
In this case this does mutate the original object(intended behavior). My question: Why does this nestedObj
seemingly hold a reference to the original object but not the first in the first solution? I don't think it has anything to do with this being a recursive function. But I was a bit confused and was wondering if someone could shed some light.