前端扁平化数据转树形数据_把平级数据变成树形数据
為了記住這個方法:轉化數據
[
{element:'圖片',id:'1',pid:'0'},//count=1
{element:'大圖片',id:'2',pid:'1'},
{element:'png',id:'3',pid:'2'},
{element:'jpeg',id:'4',pid:'2'},
{element:'gif',id:'5',pid:'2'},
{element:'gif11',id:'6',pid:'5'},
{element:'gif111',id:'7',pid:'6'},
{element:'gif222',id:'8',pid:'6'},
{element:'文字',id:'9',pid:'0'},
{element:'宋體',id:'10',pid:'9'},
{element:'宋體111',id:'11',pid:'10'},
{element:'宋體222',id:'12',pid:'10'},
{element:'黑體',id:'13',pid:'9'},
]
為以下這種格式的,為寫樹形插件做準備
具體代碼如下:
treevar data=[
{element:'圖片',id:'1',pid:'0'},//count=1
{element:'大圖片',id:'2',pid:'1'},
{element:'png',id:'3',pid:'2'},
{element:'jpeg',id:'4',pid:'2'},
{element:'gif',id:'5',pid:'2'},
{element:'gif11',id:'6',pid:'5'},
{element:'gif111',id:'7',pid:'6'},
{element:'gif222',id:'8',pid:'6'},
{element:'文字',id:'9',pid:'0'},
{element:'宋體',id:'10',pid:'9'},
{element:'宋體111',id:'11',pid:'10'},
{element:'宋體222',id:'12',pid:'10'},
{element:'黑體',id:'13',pid:'9'},
]
function transTreeData(items){
if(items.length>0){
var curPid= 0 //pid=0,為最上層節點 ,即無父節點
var parent=findChild(curPid);//數組
return parent;
}else{
return [];
}
}
//找子節點
function findChild (curPid){
var _arr = [];
var items=data;
var length=items.length;
for(var i = 0; i < length; i++){
if(items[i].pid == curPid){
var _obj = items[i];
_obj.children = findChild(_obj.id);
_arr.push(_obj);
}
}
return _arr;
}
console.log(transTreeData(data));
總結
以上是生活随笔為你收集整理的前端扁平化数据转树形数据_把平级数据变成树形数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 真静态和伪静态的区别
- 下一篇: bochs运行xp_bochs xp 镜