JavaScript:
function convert(orgin) { var result = arguments[1] ? arguments[1] : []; var level = arguments[2] ? arguments[2] : 0; var parentid = arguments[3] ? arguments[3] : 0; var isLeaf = function (id){ for(var x in orgin){ if(orgin[x]["parentid"]==id){ return false; } } return true; }; for(var x in orgin) { if(orgin[x]["parentid"]==parentid&&orgin[x]["skip_012ea834e2aa011ef16f7d846889c026"]!=1) { orgin[x]["isleaf"]=isLeaf(orgin[x]["id"])==true?1:0; orgin[x]["level"]=level; result.push(JSON.parse(JSON.stringify(orgin[x]))); //对象深拷贝 orgin[x]["skip_012ea834e2aa011ef16f7d846889c026"]=1;//标记该节点不用再遍历 if(!isLeaf(orgin[x]["id"])) { convert(orgin,result,level+1,orgin[x]["id"]); } } } return result; }
测试代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> <script type="text/javascript"> var orgin = [ { "id": 1, "name": "生产管理1", "parentid": 0 }, { "id": 2, "name": "生产管理2", "parentid": 1 }, { "id": 3, "name": "生产管理3", "parentid": 2 }, { "id": 4, "name": "生产管理4", "parentid": 0 }, { "id": 5, "name": "生产管理5", "parentid": 0 }, { "id": 6, "name": "生产管理6", "parentid": 5 } ]; function convert(orgin) { var result = arguments[1] ? arguments[1] : []; var level = arguments[2] ? arguments[2] : 0; var parentid = arguments[3] ? arguments[3] : 0; var isLeaf = function (id){ for(var x in orgin){ if(orgin[x]["parentid"]==id){ return false; } } return true; }; for(var x in orgin) { if(orgin[x]["parentid"]==parentid&&orgin[x]["skip_012ea834e2aa011ef16f7d846889c026"]!=1) { orgin[x]["isleaf"]=isLeaf(orgin[x]["id"])==true?1:0; orgin[x]["level"]=level; result.push(JSON.parse(JSON.stringify(orgin[x]))); //对象深拷贝 orgin[x]["skip_012ea834e2aa011ef16f7d846889c026"]=1;//标记该节点不用再遍历 if(!isLeaf(orgin[x]["id"])) { convert(orgin,result,level+1,orgin[x]["id"]); } } } return result; } console.log(convert(orgin)) </script> </html>