动态分层Javascript对象循环

时间:2012-09-20 15:14:57

标签: javascript loops hierarchical-data javascript-objects dynamicobject

   var treeData = {"name" : "A",  "children" : [
                         {"name" : "B", "children": [
                                 {"name" : "C", "children" :[]}
                          ]}
                   ]};

阵营之前应该是空的。应该根据需要的节点数量来定位阵列,这些节点将根据已通过的动态值进行定义。

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

1 个答案:

答案 0 :(得分:1)

以下是动态创建节点的函数示例:

function createNode(name) {
   return({name: name, children: []});
}

function addChild(node, child) {
    node.children.push(child);
    return node;
}

var treeData = createNode("");
var subChild = createNode("");
addChild(subChild, createNode("A31"));
addChild(treeData, subChild);

但我建议改用原型。

通过任何级别的“路径”查找任何节点:

function findNodeByPath(root, path) {
   var curr; 
   while(root && ((curr = path.splice(0,1)[0]) !== undefined)) {
        if (root.children) root = root.children[curr];
        else root = undefined;
   }
   return root;
}


function findNodeByName(root, namePath, create) {
   var curr; 
   while(root && ((curr = namePath.splice(0,1)[0]) !== undefined)) {
        if (root.children) {
            var found = undefined;
            for (var i = 0; !found && i < root.children.length; i++)
                if (root.children[i].name == curr) found = root.children[i];
            if (create && !found) {
                found = createNode(curr);
                addChild(root, found);
            }
            root = found;
        }
        else root = undefined;
   }
   return root;
}


var A31 = findNodeByPath(treeData, [0, 0]); // Will return the node with name A31
addChild(A31, createNode("A31 child 1"));
addChild(A31, createNode("A31 child 2"));

// second child will be accessible by:
var secondChildOfA31 = findNodeByPath(treeData, [0, 0, 1]);

// also to find node by the name:
var secondChildOfA31 = findNodeByName(treeData, ["", "A31", "A31 child 2"]);

// will create all intermenient nodes with respective names:
var veryDeepChild =  findNodeByName(treeData, ["foo", "bar", "baz", "quux", "moo"], true);

function createOuterNode(name, childNode) {
    return {name: name, children: childNode? [childNode] : []}
}

// Example to create nodes in the question:
var CNode = createOuterNode("C");
var BNode = createOuterNode("B", CNode);
var ANode = createOuterNode("A", BNode);

// Example using LOOP:
var list = ["A", "B", "C"];
var outer = undefined;
for (var i = list.length - 1; i >= 0; i--) outer = createOuterNode(list[i], outer);

// outer will contain A node with child B with child C
console.log(outer);