我计划使用 Bootstrap Treeview,其中 Json 预计如下。 我需要根据各自的输入节点动态地将元素添加到“树”
var tree = {};
tree = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
nodes: [
{
text: "Grandchild 1",
nodes : [
{
text : "GrandChild 3"
}
]
},
{
text: "Grandchild 2",
nodes : [
{
text : "GrandChild 4"
}
]
}
]
},
{
text: "Child 2"
}
]
},
{
text: "Parent 2"
},
{
text: "Parent 3"
},
{
text: "Parent 4"
},
{
text: "Parent 5"
}
];
我尝试过 array.reduce() 但无法实现。
寻找一些方法
最佳答案
您可以手动执行此操作:
alert(tree[0].nodes[0].nodes[0].nodes[0].text);// alerts "GrandChild 3"
// add a node array:
tree[0].nodes[0].nodes[0].nodes[0].nodes = [{
text: "GrandChild NEW First"
}];
console.dir(tree);
节目: Array[5]0:对象节点:Array[2]0:对象节点:Array[2]0:对象节点:Array[1]0:对象节点:Array[1]0:对象文本:“GrandChild NEW First” _proto__:对象长度:1__proto__:数组[0]文本:“GrandChild 3” _proto__:对象长度:1
对数组 1 执行相同操作:
数组[5] 1:对象 节点:数组[1] 文本:“父级 2”
tree[1].nodes = [{
text: "GrandChild NEW Second"
}];
现在您只需要代码来确定节点的深度以及在该点添加的内容(节点或文本或两者)。
编辑如果更清楚的话,最后的添加也可以这样完成:
添加一个新的节点数组,然后将一个值插入其中
tree[1].nodes = [];
tree[1].nodes.push({
text: "GrandChild NEW Second"
});
关于javascript - 在 JS 中动态创建树/嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36807055/