我正在进行树视图,我创建了一个类Node,包含一个名称和一个子列表。
class Node {
constructor(name, childNodes) {
this.name = name;
this.childNodes = childNodes;
}
}
我正在尝试在下图中创建一个看起来像对象“树”的对象。每个节点都有一个名为“nodes”的属性,即childNode-Array。 我非常接近创建相同的树,但在我的版本中,每个子节点周围都有一个额外的“数组” - 层(请参阅recTreeview() - 元素):
我不确定如何解决这个问题。必须创建数组以包含子节点。以下是创建树视图元素的代码:
function recTreeview(currentNode, treeview) {
var tempChildren = [];
currentNode.children.forEach(child => {
tempChildren.push(recTreeview(child, []));
});
treeview.push({
text: currentNode.name,
nodes: tempChildren
});
return treeview;
}
我能做些什么吗?更新:Code-Snippet:
class Node {
constructor(name, children) {
this.children = children;
this.name = name;
}
}
function recTreeview(currentNode, treeview) {
var tempChildren = [];
currentNode.children.forEach(child => {
tempChildren.push(recTreeview(child, []));
});
treeview.push({
text: currentNode.name,
nodes: tempChildren
});
return treeview;
}
child1 = new Node("child1", []);
child2 = new Node("child2", []);
parent = new Node("Parent", [child1, child2]);
var tree = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1"
},
{
text: "Child 2"
}
]
}
];
<button onClick="console.log(recTreeview(parent, []));">Wrong</button>
<button onClick="console.log(tree);">Right</button>
答案 0 :(得分:2)
额外数组来自tempChildren.push(recTreeview(child, []));
。因为您要将recTreeview
(这是一个数组)的返回值推送到子数组tempChildren
。
您应该将tempChildren
作为参数传递给tempChildren
,而不是将新数组推送到recTreeview
:
currentNode.children.forEach(child => {
recTreeview(child, tempChildren);
});
这样孩子们就会被直接推到tempChildren
数组,而不是被额外的数组recTreeview
包裹起来。
示例:强>
class Node {
constructor(name, children) {
this.children = children;
this.name = name;
}
}
function recTreeview(currentNode, treeview) {
var tempChildren = [];
currentNode.children.forEach(child => {
recTreeview(child, tempChildren);
});
treeview.push({
text: currentNode.name,
nodes: tempChildren
});
return treeview;
}
child1 = new Node("child1", []);
child2 = new Node("child2", []);
parent = new Node("Parent", [child1, child2]);
var tree = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1"
},
{
text: "Child 2"
}
]
}
];
<button onClick="console.log(recTreeview(parent, []));">Not Wrong Anymore</button>
<button onClick="console.log(tree);">Right</button>
注意:强>
如果你想在没有孩子的情况下摆脱那个空的nodes
数组,那么改变它:
treeview.push({
text: currentNode.name,
nodes: tempChildren
});
要:
var node = {
text: currentNode.name
};
if(tempChildren.length) {
node.nodes = tempChildren;
}
treeview.push(node);
如果nodes
数组不为空,则仅添加tempChildren
属性。