javascript - How to prune/delete nodes in nested/tree-like JSON? -
i have following json example represent tree.
[ { "label": "node1", "children": [ { "label": "human" }, { "label": "chimpanzee" } ] }, { "label": "node2", "children": [ { "label": "node3", "children": [ { "label": "rat" }, { "label": "mouse" } ] }, { "label": "bigrat" } ] } ]
what now, following: given list of labels (e.g. bigrat, mouse), how can delete corresponding nodes in json?
i can't head around this.
any appreciated!
thanks
since tree object array, each object has label , optional child array, need prune array elements, either in main tree array or in 1 of it's branches.
you not want use delete
delete array elements, since leaves sparse array. instead, should splice
out array elements.
you should, on other hand, use delete
remove object properties, children
once they're empty. here's code use:
function prune(array, label) { (var = 0; < array.length; ++i) { var obj = array[i]; if (obj.label === label) { // splice out 1 element starting @ position array.splice(i, 1); return true; } if (obj.children) { if (prune(obj.children, label)) { if (obj.children.length === 0) { // delete children property when empty delete obj.children; // or, delete parent altogether // result of having no more children // instead array.splice(i, 1); } return true; } } } }
now assuming tree called tree
, label wanted pruned node3
, call prune so:
var wasitpruned = prune(tree, "node3");
Comments
Post a Comment