如何递归编写代码?

时间:2017-07-08 12:35:42

标签: javascript arrays json dictionary recursion

我想通过递归将这些代码转换为更小的代码,但是我在使用for循环的地方停留了。

我有下一个字典:var structure = [];,结构为:

"path": path,
"children": []

我正在通过解析我的JSON文件来填充它。来自JSON的路径之一如下:"path": "Assignment_1/src/com",,因此我正在通过/解析路径并尝试在我的structure字典内重建此结构。第一部分,"path": "Assignment_1/",我把我的结构放在里面。第二部分"path": "Assignment_1/src/",我放在children字典里面等等。

没有递归我正在这样做:

if(path.split("/").length == 2) {
        if(type == "tree") {
            var path0 = path.split("/")[0];
            var path1 = path.split("/")[1];

            for(var j = 0; j < structure.length; j++) {
                var foundPath = structure[j]["path"];

                if(foundPath == path0) {
                    structure[j]["children"].push({
                        "path": path1,
                        "children": []
                    })
                }
            }
        }
    }

    if(path.split("/").length == 3) {
        if(type == "tree") {
            var path0 = path.split("/")[0];
            var path1 = path.split("/")[1];
            var path2 = path.split("/")[2];

            for(var j = 0; j < structure.length; j++) {
                var foundPath = structure[j]["path"];

                if(foundPath == path0) {
                    for(var k = 0; k < structure[j]["children"].length; k++) {
                        var foundPath = structure[j]["children"][k]["path"];

                        if(foundPath == path1) {
                            structure[j]["children"][k]["children"].push({
                                "path": path2,
                                "children": []
                            })
                        }
                    }
                }

                print(structure);
            }
        }
    }

现在我想统一它,所以它会自动浏览所有文件夹并填充我的structure字典。我从while循环开始,但这部分:

structure[j]["children"].push({ })
structure[j]["children"][k]["children"].push({ })

太难编程了。任何帮助或建议都会对我有所帮助!

更新

输入是(一部分):

{
  "path": "Folder_1/src/com",
  "mode": "040000",
  "type": "tree"
},

输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

var inputs = [
    {
      "path": "Folder_1/src/com",
      "mode": "040000",
      "type":"tree"
    },
    {
      "path": "Folder_1/src/com",
      "mode": "040000",
      "type":"tree"
    },
    {
      "path": "Folder_2/docs/files",
      "mode": "040000",
      "type":"tree"
    }   
],
output = [];

inputs.forEach( function( input ) {
    parse( input.path.split('/'), output );
} );

function parse( input, into ){
    var split = input,
      first = split.shift(),
      newItem = { 'src': first, 'children': [] };     

    if( split.length ){
        parse( split, newItem.children );   
    }   
  if( ! into.find(function(item){return item.src == first } ) ){
        into.push( newItem );
  }
}

console.log( output );

Jfiddle

虽然我没有考虑type == tree,不管是什么。