简体   繁体   中英

Recursive Javascript: child->parent relationship

I'm trying to walk a chain of parent->child relationships until we reach a parent that does not have its own parent. If the child has a parent, then we store that parent object in the array along with any parents of that parent. If the parent doesn't have a parent, we store an empty array.

Here's some pseudo-JSON showing the data-structure I want.

Node3 = { // Node 3
   parent: { // Node 2
      parent: { // Node 1
         parent: null,
         parentTree: []
      },
      parentTree: [Node1]
   },
   parentTree: [Node2, Node1]
}

Here is the constructor function and the recursive method so far...

function Node(parent) {
    this.parent = typeof parent !== 'undefined' ? parent : null;
}

Node.prototype.getParentTree = function() {
    if(typeof this.parentTree === "undefined") {
        if (this.parent !== null) {
            this.parentTree = this.parent.getParentTree();
            this.parentTree.push(this.parent);
        } else {
            this.parentTree = [];
        }
    }
    return this.parentTree;
}

Here is how I'm testing the method:

var node1 = new Node();
var node2 = new Node(node1);
var node3 = new Node(node2);

node3.getParentTree();

The problem with the current method is that the parentTree for node1, node2, and node3 all have length === 2. When you inspect the objects in parentTree they contains pairs of sub-objects to infinity.

 this.parentTree = this.parent.getParentTree(); this.parentTree.push(this.parent); 

That way, both the parent's and child's parentTree refer to the very same Array object - so you're appending the new node to the parent's tree as well.

Create a copy of the array by using slice :

return this.parentTree.slice(); // every time the getter is called

or

this.parentTree = this.parent.getParentTree().slice(); // only for manipulating

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM