如何遍历嵌套数组?

时间:2017-05-22 12:25:01

标签: javascript

我试图通过从根节点遍历到叶节点来保存每个节点的路径。

例如,我在层次结构中有这样的节点:

Node - 1
     Node-1-1
       Node-1-1-1

每个节点的预期输出:

So for Node - 1 I would like to have value in property path : /myPath/Node - 1
So for Node-1-1 I would like to have value in property path : /myPath/Node - 1/Node-1-1
So for Node-1-1-1 I would like to have value in property path : /myPath/Node - 1/Node-1-1/Node-1-1-1

但我获得的路径如下所示,我的代码为 Node-1-1-1

"/myPath/Node-1-1-1"

但预计会如下:

/myPath/Node - 1/Node-1-1/Node-1-1-1  (becuase Node-1-1-1 belongs to Node-1-1 but Node-1-1 in turn belongs to Node - 1).

演示:



var  tree =  JSON.parse('[{"name":"Node","nodes":[{"name":"Node-1","nodes":[{"name":"Node-1-1","nodes":[{"name":"Node-1-1-1","nodes":[],"path":null}],"path":null}],"path":null}],"path":null}]');

traverseTree(tree);
console.log(tree);
 function traverseTree(nodes)
    {
        nodes.forEach(function (node) {
        node.path= getPath(node.name) 
            if (node.nodes) {
                traverseTree(node.nodes);
            }
        });
    }
    
    function getPath(name)
    {
       var path = "/myPath/";
       path = path + name;
       return path;
    }




1 个答案:

答案 0 :(得分:1)

您可以收集路径中的所有节点,然后使用该阵列获取节点的整个路径。



After:=ActiveCell

var  tree =  JSON.parse('[{"name":"Node","nodes":[{"name":"Node-1","nodes":[{"name":"Node-1-1","nodes":[{"name":"Node-1-1-1","nodes":[],"path":null}],"path":null}],"path":null}],"path":null}]');

function traverseTree(nodes, path) {
    path = path || [];
    nodes.forEach(function (node) {
        node.path = getPath(path.concat(node.name));
        if (node.nodes) {
            traverseTree(node.nodes, path.concat(node.name));
        }
    });
}
    
function getPath(name) {
   var path = "/myPath/";
   path = path + name.join('/');
   return path;
}

traverseTree(tree);
console.log(tree);




带有给定前缀

的较短版本



.as-console-wrapper { max-height: 100% !important; top: 0; }

var  tree =  JSON.parse('[{"name":"Node","nodes":[{"name":"Node-1","nodes":[{"name":"Node-1-1","nodes":[{"name":"Node-1-1-1","nodes":[],"path":null}],"path":null}],"path":null}],"path":null}]');

function traverseTree(nodes, path) {
    path = path || [];
    nodes.forEach(function (node) {
        var p = path.concat(node.name);
        node.path = p.join('/')
        if (node.nodes) {
            traverseTree(node.nodes, p);
        }
    });
}

traverseTree(tree, ['', 'myPath']);
console.log(tree);