javascript - How can a JS tree node retain a reference to its parent without becoming circular? -
i'd have tree structure each node can have reference parent node, so:
class tree { constructor(name, parent = null) { this.name = name; this.children = []; this.parent = parent; } appendchild(name) { this.children.push(new tree(name, this)); } } let mytree = new tree("sarah"); mytree.appendchild("laura");
the problem such structure impossible represent in json, because it's circular: sarah contains reference child laura contains reference parent sarah contains reference child laura, , on.
what i'd child have pointer parent, doesn't evaluated full parent. don't think that's possible. should do?
add custom tojson method, resolves references strings id, add fromjson method opposite, e.g:
tree.tojson=function(tree,i=0){ tree.lookup=i; tree.children.foreach(function(child){ child.parent=i; tree.tojson(child,++this.i); },{i}); if(!i) return json.stringify(tree); } tree.fromjson=function(tree,lookup=new map()){ if(typeof tree==="string") tree=json.parse(tree); lookup.set(tree.lookup,tree); tree.children.foreach(function(child){ child.parent=lookup.get(child.parent); tree.fromjson(child,lookup); }); return tree; }
but if talking parent reference, might easier simple remove it, , add later:
//tojson tree.children.foreach(function(child){ delete child.parent; }); //fromjson tree.children.foreach(function(child){ child.parent=tree; });
Comments
Post a Comment