樹形數據結構:
樹形數據結構是一類重要的非線性數據結構。樹形數據結構能夠表示數據表素之間一對多的關係。其中以樹與二叉樹最爲經常使用,直觀看來,樹是以分支關係定義的層次結構。樹形數據結構在客觀世界中普遍存在,如人類社會的族譜和各類社會組織機構均可用樹形數據結構來形象表示。
扁平數據結構: 以下所示
1、扁平轉樹形
var data=[
{pid:0,id:'a',value:'陝西'},
{pid:'a',id:01,value:'西安'},
{pid:01,id:301,value:'雁塔區'},
{pid:01,id:302,value:'高新區'},
{pid:'a',id:02,value:'渭南'},
{pid:'a',id:03,value:'咸陽'},
{pid:0,id:'b',value:'廣東'},
{pid:'b',id:11,value:'廣州'},
{pid:'b',id:12,value:'深圳'},
{pid:'b',id:13,value:'潮汕'},
{pid:0,id:'c',value:'湖南'},
{pid:'c',id:21,value:'長沙'},
{pid:'c',id:22,value:'常德'},
{pid:'c',id:23,value:'岳陽'},
];
function toTree(data){
let cloneData = JSON.parse(JSON.stringify(data)) // 對源數據深度克隆
let tree = cloneData.filter((father)=>{ //循環全部項
let branchArr = cloneData.filter((child)=>{
return father.id == child.pid;//返回每一項的子級數組
});
if(branchArr.length>0){
father.children = branchArr; //若是存在子級,則給父級添加一個children屬性,並賦值
}
return father.pid==0;//返回第一層
});
return tree; //返回樹形數據
}
var tree=toTree(data);
console.log(tree);
//遞歸方法:
function toTree(data) {
// 刪除 全部 children,以防止屢次調用
data.forEach(function (item) {
delete item.children;
});
// 將數據存儲爲 以 id 爲 KEY 的 map 索引數據列
var map = {};
data.forEach(function (item) {
map[item.id] = item;
});
var val = [];
data.forEach(function (item) {
// 以當前遍歷項,的pid,去map對象中找到索引的id
var parent = map[item.pid];
// 好繞啊,若是找到索引,那麼說明此項不在頂級當中,那麼須要把此項添加到,他對應的父級中
if (parent) {
(parent.children || ( parent.children = [] )).push(item);
} else {
//若是沒有在map中找到對應的索引ID,那麼直接把 當前的item添加到 val結果集中,做爲頂級
val.push(item);
}
});
return val;
}
console.log(toTree(data))
2、樹形轉扁平
var data=[
{id: "a",pid: 0,value: "陝西",children:[
{id: 01,pid: "a",value: "西安"},
{id: 02,pid: "a",value: "渭南"},
{id: 03,pid: "a",value: "咸陽"},
]},
{id: "b",pid: 0,value: "廣東",children:[
{id: 11,pid: "b",value: "廣州"},
{id: 12,pid: "b",value: "深圳"},
{id: 13,pid: "b",value: "潮汕"},
]},
{id: "c",pid: 0,value: "湖南",children:[
{id: 21,pid: "c",value: "長沙"},
{id: 22,pid: "c",value: "常德"},
{id: 23,pid: "c",value: "岳陽"},
]},
];
function toLine(data){
return data.reduce((arr, {id, value, pid, children = []}) =>
arr.concat([{id, value, pid}], toLine(children)), [])
return result;
}
var listarr=toLine(data);
console.log(listarr);