javascript - 在 JS 中动态创建树/嵌套 JSON

标签 javascript json twitter-bootstrap

我计划使用 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/

相关文章:

javascript - JSON.stringify 抛出 RangeError : Invalid string length for huge objects

javascript - AngularJS 如果复选框是选中显示

Java : Replace \"with " and\/with/

json - Axios PUT请求无效,但GET有效

html - Bootstrap CSS 覆盖我的自定义 CSS

javascript - 由于变量尚未加载,无法绑定(bind)到子组件的属性?

javascript - 使用 BrowserMobProxy 配置 WebDriverIO

javascript - 自动访问 json 中的字母数字索引

PHP 进度条 : % Of 2 Numbers

javascript - 如何将关闭按钮添加到 snackbar