在做一些前端开发的时候,经常会遇到后端返回一个树形结构,但是前端需要展示的是一个列表,但是这个列又需要体现其层级结构,今天抽空特意写了一个树形结构转列表的方法,以供参考:
var dataTree = [ {id:1,name:'技术部',children:[ {id:2,name:'前端开发',children:[ {id:4,name:'javascript',children:[ {id:5,name:'原生JS',children:[ {id:6,name:'ECMAScript'} ]} ]}, {id:7,name:'jquery'} ]}, {id:8,name:'前后端分离',children:[ {id:9,name:'VUE',children:[ {id:10,name:'VUECLI'} ]}, {id:11,name:'AngularJS'}, ]} ]}, {id:12,name:'商务部',children:[ {id:13,name:'销售部',children:[ {id:14,name:'客服部',children:[ {id:15,name:'客服一部'}, {id:16,name:'客服二部'} ]} ]}, {id:17,name:'外交部'} ]} ];
树形结构转列表:
function treeToList(datas){ var arr = []; formateData(datas,0); function formateData(datas,level){ var level = level || 0; level ++; for(var i in datas){ arr.push({id:datas[i]['id'],name:datas[i]['name'],level:level,line:getStr(level)}); if(datas[i].children){ formateData(datas[i].children,level); } } } function getStr(level){ var str = ''; for(var i=1; i<level; ++i){ str += '—'; } return level ==1 ? '' : '|'+str } return arr; }
测试示例:
var treeList = treeToList(dataTree); console.log(treeList);
示例:
for(var i in treeList){ console.log(treeList[i]['line'] + treeList[i].name); }
抛转引玉,需要的自己调整即可。