Javascript JS树节点如何保留对其父节点的引用而不成为循环?

Javascript JS树节点如何保留对其父节点的引用而不成为循环?,javascript,json,Javascript,Json,我希望有一个树结构,其中每个节点都可以引用其父节点,如下所示: 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

我希望有一个树结构,其中每个节点都可以引用其父节点,如下所示:

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表示,因为它是循环的:Sarah包含对她的孩子Laura的引用,其中包含对她的父母Sarah的引用,其中包含对她的孩子Laura的引用,等等

我真正想要的是,孩子只需要有一个指向其父的指针,而不会被计算成完整的父对象。但我认为这是不可能的。那么我该怎么办呢?

添加一个自定义的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;
});
添加一个自定义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;
});

请澄清,您在谈论JSON。在这个问题上它必须做什么?您的目标是用JSON和/或javascript表示该树吗?a)不要在JSON中包含
parent
字段;或者b)为
对象指定一个ID,并在JSON中使用该ID而不是对象;我同意其他的评论,我想补充一句:想想你将如何使用你的树。这种结构是不一致的:您在两个点上有相同的信息,这可能导致A的子项列表与A被标识为B的父项之间的不一致。如果您不需要从树的顶部向下浏览,请不要包含“parent”属性。请澄清,您在某个点上谈论的是JSON。在这个问题上它必须做什么?您的目标是用JSON和/或javascript表示该树吗?a)不要在JSON中包含
parent
字段;或者b)为
对象指定一个ID,并在JSON中使用该ID而不是对象;我同意其他的评论,我想补充一句:想想你将如何使用你的树。此结构不一致:您在两个点上有相同的信息,这可能导致A的子项列表与A被标识为B的父项之间不一致。如果您不需要从树的顶部向下浏览,请不要包含“parent”属性。