I have something similar to a tree structure in my javascript program and I want to remove a child from it, I used a recursive approach to traverse the tree but I am quite stuck in deleting a node from the tree.
In contrast, I will get an ID as a parameter and I should check it against the child.metadata.id and delete the child if it maches with the ID.
Note : I have certain type of child nodes in my graph where it divides it path based on its type 'true' or 'false' that is if the type of the child node in the metadata is if/empty.
Here is the sample tree structure.
var graph =
{
"metadata": {"id": "sms_in", "type": "api", "optionsDivId": "div_sms_in", "options": {}},
"data": {
"true": {
"isEmpty1": {
"metadata": {
"id": "isEmpty1",
"type": "empty",
"optionsDivId": "div_isEmpty1",
"options": {}
},
"data": {
"true": {
"sms1": {
"metadata": {
"id": "sms1",
"type": "api",
"optionsDivId": "div_sms1",
"options": {}
}, "data": {"true": {}, "false": false}
}
},
"false": {
"dbInsert1": {
"metadata": {
"id": "dbInsert1",
"type": "dbInsert",
"optionsDivId": "div_dbInsert1",
"options": {}
},
"data": {
"true": {
"sms2": {
"metadata": {
"id": "sms2",
"type": "api",
"optionsDivId": "div_sms2",
"options": {}
}, "data": {"true": {}, "false": false}
}
}, "false": false
}
}
}
}
}
}, "false": false
}
};
and this is my traverse function
var traverse = function (current) {
if( current == 'undefined' ) return ;
var currentChildId = current['metadata']['id'];
var currentChildType = current['metadata']['type'];
console.log('visiting : ', currentChildId);
if (currentChildType == 'if' || currentChildType == 'empty') {
for(var childKeyType in current['data']){
for( var childKey in current['data'][childKeyType]){
var child = current['data'][childKeyType][childKey];
traverse(child);
}
}
} else {
for (var childKey in current['data']['true']) {
var child = current['data']['true'][childKey];
traverse(child);
}
}
};
Can someone help me to complete the delete function ?
function popChild(current, childId){
if( current == 'undefined' ) return ;
var currentChildId = current['metadata']['id'];
var currentChildType = current['metadata']['type'];
if(currentChildId == childId){
delete current;
return;
}
console.log('visiting : ', currentChildId);
if (currentChildType == 'if' || currentChildType == 'empty') {
for(var childKeyType in current['data']){
for( var childKey in current['data'][childKeyType]){
var child = current['data'][childKeyType][childKey];
popChild(child, childId, );
}
}
} else {
for (var childKey in current['data']['true']) {
var child = current['data']['true'][childKey];
popChild(child, childId);
}
}
}
delete current;and expect it to reflect on the original object. Instead I would maybe try to create a recursive function that simply generates a path to the child you want to delete and then apply that string to delete the child from the top of the hierarchy.