把平級數據變成樹形數據

爲了記住這個方法:轉化數據javascript

[
    {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'},
]

爲如下這種格式的,爲寫樹形插件作準備html

clipboard.png

具體代碼以下:java

<!DOCTYPE html>
<html>
<head>
    <title>tree</title>
</head>
<body>
</body>
</html>
<script type="text/javascript">
var 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));
</script>
相關文章
相關標籤/搜索