Within my coding project, I came across a nested JSON object that looks like this:
var jsonObj =
{ "level1" :
{ "status" : true,
"level2" : {} // with the potential to extend further to level 3, 4, and beyond
}
}
My objective is simple - I aim to access Level2 and insert a new Level3 object into it. Essentially, the desired code snippet appears as follows, yet due to the varying levels, I require a function capable of traversing through the object.
obj.Level1.Level2.Level3 = { 'status' : true}
Presented here is an excerpt of my code:
function updateStatusForLevel(nestedObj, categoryHierarchy){
// The passed categoryHierarchy is ['Level1', 'Level2', 'Level3'];
var obj = nestedObj;
angular.forEach(categoryHierarchy, function(value, key){
obj = obj[value];
if (key === categoryHierarchy.length - 1 && angular.isUndefined(obj)){
obj[value] = {}; // Here, I intend to include 'Level3' = {}
}
});
obj.status = 'true'; // Finally, the status gets updated
console.info("The original obj is " + JSON.stringify(nestedObj));
}
However, it seems like there might be a crucial element missing in my approach. Upon execution of the operation, the initial nestedObj remains unaltered (with only the obj
being modified). I had initially anticipated this process to be relatively straightforward when navigating a deeply nested JSON structure. Why does the shallow copy fail to reflect the changes made to the original object?