树形数据结构: 树形数据结构是一类重要的非线性数据结构。树形数据结构可以表示数据表素之间一对多的关系。其中以树与二叉树最为常用,直观看来,树是以分支关系定义的层次结构。树形数据结构在客观世界中广泛存在,如人类社会的族谱和各种社会组织机构都可用树形数据结构来形象表示。
扁平数据结构: 如下所示
一、扁平转树形
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
;
}
return father
.pid
==0;
});
return tree
;
}
var tree
=toTree(data
);
console
.log(tree
);
function toTree(data
) {
data
.forEach(function (item
) {
delete item
.children
;
});
var map
= {};
data
.forEach(function (item
) {
map
[item
.id
] = item
;
});
var val
= [];
data
.forEach(function (item
) {
var parent
= map
[item
.pid
];
if (parent
) {
(parent
.children
|| ( parent
.children
= [] )).push(item
);
} else {
val
.push(item
);
}
});
return val
;
}
console
.log(toTree(data
))
二、树形转扁平
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
);
转载请注明原文地址: https://mac.8miu.com/read-498505.html