简体   繁体   English

动态 Javascript 树结构

[英]Dynamic Javascript Tree Structure

I would like to build the hierarchy dynamically with each node created as a layer/level in the hierarchy having its own array of nodes.我想动态地构建层次结构,每个节点创建为层次结构中的层/级别,具有自己的节点数组。 THIS SHOULD FORM A TREE STRUCTURE.There should be a root node, and an undefined number of nodes and levels to make up the hierarchy size.这应该形成一个树结构。应该有一个根节点,以及一个未定义数量的节点和级别来组成层次结构大小。 Nothing should be fixed besides the root node.除了根节点之外,什么都不应该被修复。 I do not need to read or search the hierarchy, I need to construct it.我不需要阅读或搜索层次结构,我需要构建它。 The array should start {"name" : "A", "children" : []} and every new node as levels would be created {"name" : "A", "children" : [HERE-{"name" : "A", "children" : []}]}.数组应该以 {"name" : "A", "children" : []} 开头,并且每个新节点都会被创建为级别 {"name" : "A", "children" : [HERE-{"name" : “A”,“儿童”:[]}]}。 In the child array, going deeper and deeper.在子阵中,越走越深。 Basically the array should have no values before the call, except maybe the root node.基本上数组在调用之前应该没有值,除了根节点。 After the function call, the array should comprise of the required nodes of a number that may vary with every call depending on the results of a database query.在函数调用之后,数组应该包含一个数字的所需节点,这些节点可能会随着每次调用而变化,具体取决于数据库查询的结果。 Every child array will contain one or more node values.每个子数组将包含一个或多个节点值。 There should be a minimum of 2 node levels, including the root.至少应该有 2 个节点级别,包括根节点。 It should initially be a Blank canvas, that is no predefined array values.它最初应该是一个空白画布,即没有预定义的数组值。

So your nodes have a name: property and a children: array property.所以你的节点有一个name:属性和一个children:数组属性。

Databases typically store trees in tables as数据库通常将树存储在表中

node-id, parent-id, value1, ..., valueN

(you can get certain advantages if you store depth-first visit order and depth-first return order; ask in comments if you need the details). (如果您存储深度优先访问顺序和深度优先返回顺序,您可以获得某些优势;如果您需要详细信息,请在评论中询问)。

If you make a single query and get this data into JSON, you will have something like (for your illustration),如果您进行单个查询并将此数据转换为 JSON,您将得到类似的内容(为了您的说明),

[{id: "0", parent: "-1", name: "A2"}, {id: "1", parent: "0", name: "A3"}, 
 {id: "2", parent: "1", name: "A31"}, {id: "3", parent: "2", name: "A311"}, 
 {id: "4", parent: "2", name: "A312"}]

You can convert this into {name: children:} format with the following code:您可以使用以下代码将其转换为{name: children:}格式:

  // data is an array in the above format
function toTree(data) {
   var childrenById = {}; // of the form id: [child-ids]
   var nodes = {};        // of the form id: {name: children: }
   var i, row;
   // first pass: build child arrays and initial node array
   for (i=0; i<data.length; i++) {
       row = data[i];
       nodes[row.id] = {name: row.name, children: []};
       if (row.parent == -1) { // assume -1 is used to mark the root's "parent"
          root = row.id; 
       } else if (childrenById[row.parent] === undefined) {
          childrenById[row.parent] = [row.id];
       } else {
          childrenById[row.parent].push(row.id);
       }
   }
   // second pass: build tree, using the awesome power of recursion!
   function expand(id) {
       if (childrenById[id] !== undefined) {
           for (var i=0; i < childrenById[id].length; i ++) {
               var childId = childrenById[id][i];
               nodes[id].children.push(expand(childId));
           }
       }
       return nodes[id];
   }
   return expand(root);
}

See http://jsfiddle.net/z6GPB/ for a working example.有关工作示例,请参阅http://jsfiddle.net/z6GPB/

    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));

Output输出

{
  "name": "A",
  "children": [
    {
      "name": "B1",
      "children": {
        "name": "C1",
        "children": [
          {
            "name": "D1",
            "children": []
          },
          {
            "name": "D2",
            "children": []
          }
        ]
      }
    },
    {
      "name": "B2",
      "children": [
        {
          "name": "C2",
          "children": []
        }
      ]
    }
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM