I found a good piece of code on SO that I only partially understand. If you could help me understand what is happening with myObj
in the second loop of this recursive function when the function no longer points to myObj
(instead it points to tmpObj
yet it still adds onto it.
var myObj = {};
function addProps(obj, arr, val) { // in the first run obj = myObj
if (typeof arr == 'string')
arr = arr.split(".");
obj[arr[0]] = obj[arr[0]] || {};
var tmpObj = obj[arr[0]];
if (arr.length > 1) {
arr.shift();
addProps(tmpObj, arr, val); // whilst recursing, tmpObj becomes obj (as function parameter), so why myObj keeps being changed as well?
}
else
obj[arr[0]] = val;
return obj;
};
addProps(myObj, 'sub1.sub2.propA', 1);
Link to the original piece of code : https://stackoverflow.com/a/34205057