Json Listデータは再帰的に階層Jsonに変換される.

9532 ワード

{"id":"1","parentId":"0","name":"      "},
{"id":"2","parentId":"1","name":"  "},
{"id":"3","parentId":"1","name":"      "},
{"id":"4","parentId":"2","name":"a    "},
{"id":"5","parentId":"4","name":"  "},
{"id":"6","parentId":"5","name":"    "},
{"id":"7","parentId":"6","name":";   "},
{"id":"8","parentId":"7","name":"    "},
{"id":"9","parentId":"5","name":"     "},
{"id":"10","parentId":"9","name":"        "}
];
var getJsonTree=function(data,parentId){
        var itemArr=[];
        for(var i=0;i<data.length;i++){ 
            var node=data[i];
            //data.splice(i, 1)
             if(node.parentId==parentId ){ 
                var newNode={id:node.id,title:node.name,nodes:getJsonTree(data,node.id)};
                itemArr.push(newNode);              
             }
        }
        return itemArr;
    } 
var jsonArray = getJsonTree(data,'0');
console.log(jsonArray);