动态 Javascript 树结构

use*_*586 3 javascript loops dynamic-data tree-structure javascript-objects

我想动态构建层次结构,每个节点创建为层次结构中的层/级别,具有自己的节点数组。这应该形成一个树结构。应该有一个根节点,以及未定义数量的节点和级别来构成层次结构的大小。除了根节点之外,不应修复任何内容。我不需要阅读或搜索层次结构,我需要构建它。该数组应以 {"name" : "A", "children" : []} 开头,并且将创建每个新节点作为级别 {"name" : "A", "children" : [HERE-{"name" : “A”,“孩子”:[]}]}。在子数组中,越陷越深。基本上,数组在调用之前应该没有值,除了根节点之外。函数调用之后,数组应包含所需节点的数量,这些节点的数量可能随每次调用而变化,具体取决于数据库查询的结果。每个子数组将包含一个或多个节点值。至少应有 2 个节点级别(包括根)。它最初应该是一个空白画布,没有预定义的数组值。

bal*_*afi 5

    function Tree(name,child){
        this.name = name;
        this.children = child || [];
        this.addNode = function (parent){
            this.children = parent;
        }
        this.addChild = function (parentName){
            this.children.push(new Tree(parentName));
        }
    }

    var tree = new Tree("A"); // create a tree (or a portion of a tree) with root "A" and empty children
    tree.addChild("B1");   // A -> B1
    tree.addChild("B2");   // A -> B2
    var subTree1 = new Tree("C1"); // create a sub tree
    subTree1.addChild("D1");   // C1 -> D1
    subTree1.addChild("D2");   // C1 -> D2
    tree.children[0].addNode(subTree1);   // add this sub tree under A->B1
    // Tree now is:  A--> B1
    //                      C1
    //                        D1
    //                        D2
    //                    B2
    tree.children[1].addChild("C2");
    // Tree now is:  A--> B1
    //                      C1
    //                        D1
    //                        D2
    //                    B2
    //                      C2
    //tree.children[0].addChild("C4");
    // Tree now is:  A--> B1
    //                      C1
    //                        D1
    //                        D2
    //                      C4
    //                    B2
    //                      C2    
    console.log(JSON.stringify(tree));
Run Code Online (Sandbox Code Playgroud)

输出

{
  "name": "A",
  "children": [
    {
      "name": "B1",
      "children": {
        "name": "C1",
        "children": [
          {
            "name": "D1",
            "children": []
          },
          {
            "name": "D2",
            "children": []
          }
        ]
      }
    },
    {
      "name": "B2",
      "children": [
        {
          "name": "C2",
          "children": []
        }
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)