2017-07-28 22 views
1

我想有一個樹結構,其中每個節點可以具有到它的父節點的引用,像這樣:JS樹節點如何保留對其父代的引用而不成爲循環?

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"); 

的問題是,這樣的結構是不可能的JSON來表示,因爲它是圓形:莎拉提到她的孩子勞拉,其中提到她的父母莎拉,其中提到她的孩子勞拉,等等。

我真的很喜歡的是,孩子只要有一個指針到它的父母,那不會被評估到完整的父母。但我不認爲這是可能的。所以我該怎麼做?

+3

請澄清,你談論的JSON在某些時候。這個問題需要做什麼?你的目標是用JSON和/或JavaScript代表那棵樹嗎? – Salketer

+1

要麼a)不要在你的JSON中包含'parent'字段;或者b)給你的'Tree'對象一個ID並使用ID代替JSON中的對象;或c)查看[JSON指針](https://tools.ietf.org/html/rfc6901)。 –

+0

我同意其他評論,我想補充一句:想想你將如何使用你的樹。這種結構是不一致的:你有兩個相同的信息,這可能導致A的子項列表與A被識別爲B的父項的事實不一致。如果你不需要瀏覽你的樹自下而上,不包含「父」屬性。 – dgiugg

回答

0

添加自定義的toJSON方法,它解析爲字符串引用內容的ID,然後添加其他fromJSON方法則正好相反,例如:

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; 
} 

但如果只是談論父母參考,它可能會更容易,簡單地刪除它,並在稍後添加它:

//toJSON 
tree.children.forEach(function(child){ 
    delete child.parent; 
}); 

//fromJSON 
tree.children.forEach(function(child){ 
child.parent=tree; 
}); 
相關問題