2

I am working on a treeview and I build a simple Node-Class: It consists of a name and an array of children:

class Node {
  constructor(name, childNodes) {
    this.name = name;
    this.childNodes = childNodes;
  }
}

Now my aim is to create a function that returns an object like this:

var tree = [
  {
    text: 'Parent 1',
    nodes: [
      {
        text: 'Child 1',
        nodes: [
          {
            text: 'Grandchild 1'
          }
        ]
      },
      {
        text: 'Child 2'
      }
    ]
  },
  {
    text: 'Parent 2'
  },
];

I tried using a recursive method. It starts with an empty array and adds children until there are no more left:

function recTreeview(currentNode, treeview) {
  var tempChildren = [];
  currentNode.childNodes.forEach(child => {
    tempChild.push(recTreeview(child, treeview));
  });
  return treeview.push({
    text: currentNode.name,
    nodes: tempChildren
  })
}

But something with the recursive Treeview Function has to be wrong. When I create the tree and try to open it in the chrome dev console, it just shows a "5" instead of something like (5) [{…}, {…}, {…}, {…}, {…}]. What did I do wrong?

tree = recTreeview(parent, []);
tree;

1 Answer 1

2

You are returning the result of the push and not the actual treeview.

As per the Array.prototype.push() docs

Return value
The new length property of the object upon which the method was called.


So instead of return treeview.push(...) do treeview.push(...) and then return treeview

function recTreeview(currentNode, treeview) {
  var tempChildren = [];
  currentNode.childNodes.forEach(child => {
    tempChild.push(recTreeview(child, treeview));
  });
  treeview.push({
    text: currentNode.name,
    nodes: tempChildren
  });

  return treeview;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.