I am encountering a critical issue with a recursive function. Here is the code snippet of my recursive function:
iterateJson(data, jsonData, returnedSelf) {
var obj = {
"name": data.groupName,
"size": 4350,
"type": data.groupType
};
if (data.parentGroupName == jsonData.name) {
jsonData.children.push(obj);
} else {
if (jsonData.children) {
for (var i = 0; i < jsonData.children.length; i++) {
if (data.parentGroupName == jsonData.children[i].name) {
jsonData.children[i].children.push(obj);
elementFound = true;
break;
}
}
if (elementFound) {
return jsonData;
} else {
if (jsonData.children) {
for (i = 0; i < jsonData.children.length; i++) {
if (elementFound) {
return jsonData;
} else {
jsonData = jsonData.children[i];
jsonData = returnedSelf.iterateJson(data, jsonData, returnedSelf);
}
}
}
}
}
}
return jsonData;
},
The issue I am facing is that in the second for loop, (jsonData.children.length)
The problem arises when my jsonData variable gets altered. How can I preserve the original parent jsonData?
I hope my question is clear. I will provide further clarification to make it more concise. Let's say initially jsonData contains 5 elements, and I enter the loop, take the first child as the new jsonData, and call this function again. When the condition is met, instead of returning to the loop with the original 5-element jsonData, it has the new json data which is the first child element of the original jsonData.
My query is how can I maintain the parent jsonData with 5 elements.