0

Consider the following code:

class Node {
  constructor(data = null, parent = null) {
    this.data = data;
    this.parent = parent;
    this.children = [];
  }

  appendChild(data) {
    this.children.push(new Node(data, this.root));
    return this.root;
  }

  toString() {
    return this.data;
  }
}

class NTree {
  constructor(data) {
    this.root = null;
  }

  addRoot(data) {
    this.root = new Node(data);
  }

  find(data) {
    if (this.root.data === data) {
      return this.root;
    }
  }

  appendChild(data) {
    this.root.appendChild(data);
  }

  toString() {
    console.log(this.root);
  }
}

const t = new NTree();
t.addRoot(1);
t.appendChild(2);
t.appendChild(3);
t.appendChild(4);

console.log(t);

The outputs looks as follows:

NTree {
  root: Node { data: 1, parent: null, children: [ [Node], [Node], [Node] ] }
}

How can I convert the above output to this:

NTree {
  root: Node { data: 1, parent: null, children: [ 2, 3, 4 ] }
}
4
  • try t.push(2) instead of t.appendChild(2)
    – Layhout
    May 20 at 2:04
  • @Layhout and how does it help?
    – Cody
    May 20 at 2:32
  • 2
    Node only logs 2 levels deep before it starts displaying placeholders. If you want to log more, then you can use one of these options How can I get the full object in Node.js's console.log(), rather than '[Object]'? May 20 at 3:19
  • Why do you want to print the root node in a kind of object notation, while you want to print the children as integers. What if those children have children? Secondly, you ask about toString(), but that is never called in your code. BTW, the appendChild methond on the Node class references an unexisting this.root. Your parent links are not set up correctly.
    – trincot
    May 20 at 6:44

1 Answer 1

0

Just do this:

console.log(JSON.stringify(t.root, null, 4));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.