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;