一、核心代码
function recursionTreeData (
nodeList = [ ] ,
cNode,
params = { id : 'id' , pId : 'pId' , name : 'name' , pName : 'pName' } ,
) {
let temp = [ ] . concat ( nodeList)
if ( cNode) {
for ( let i = 0 ; i < temp. length; i++ ) {
if ( cNode. id === temp[ i] [ params. pId] ) {
let opt = {
id : temp[ i] [ params. id] ,
pId : temp[ i] [ params. pId] ,
name : temp[ i] [ params. name] ,
pName : temp[ i] [ params. pName] ,
children : [ ] ,
}
temp. splice ( i, 1 )
i--
opt. children = recursionTreeData ( temp, opt)
cNode. children. push ( opt)
}
}
return cNode. children
} else {
let treeData = [ ]
for ( let i = 0 ; i < temp. length; i++ ) {
if ( ! temp[ i] [ params. pId] || temp[ i] [ params. pId] < 0 ) {
let opt = {
id : temp[ i] [ params. id] ,
pId : temp[ i] [ params. pId] ,
name : temp[ i] [ params. name] ,
pName : temp[ i] [ params. pName] ,
children : [ ] ,
}
temp. splice ( i, 1 )
i--
opt. children = recursionTreeData ( temp, opt)
treeData. push ( opt)
}
}
return treeData
}
}
二、示例代码
let arr = [
{
id : 610 ,
pId : null ,
name : '陕西省' ,
pName : null ,
} ,
{
id : 610100000000 ,
pId : 610 ,
name : '西安市' ,
pName : '陕西省' ,
} ,
{
id : 610200000000 ,
pId : 610 ,
name : '铜川市' ,
pName : '陕西省' ,
} ,
{
id : 610300000000 ,
pId : 610 ,
name : '宝鸡市' ,
pName : '陕西省' ,
} ,
{
id : 110100000000 ,
pId : null ,
name : '北京市' ,
pName : null ,
} ,
{
id : 110101000000 ,
pId : 110100000000 ,
name : '东城区' ,
pName : '北京市' ,
} ,
{
id : 110102000000 ,
pId : 110100000000 ,
name : '西城区' ,
pName : '北京市' ,
} ,
]
console. log ( recursionTreeData ( arr) )
三、示例结果
[
{
"id" : 610 ,
"pId" : null ,
"name" : "陕西省" ,
"pName" : null ,
"children" : [
{
"id" : 610100000000 ,
"pId" : 610 ,
"name" : "西安市" ,
"pName" : "陕西省" ,
"children" : [ ]
} ,
{
"id" : 610200000000 ,
"pId" : 610 ,
"name" : "铜川市" ,
"pName" : "陕西省" ,
"children" : [ ]
} ,
{
"id" : 610300000000 ,
"pId" : 610 ,
"name" : "宝鸡市" ,
"pName" : "陕西省" ,
"children" : [ ]
}
]
} ,
{
"id" : 110100000000 ,
"pId" : null ,
"name" : "北京市" ,
"pName" : null ,
"children" : [
{
"id" : 110101000000 ,
"pId" : 110100000000 ,
"name" : "东城区" ,
"pName" : "北京市" ,
"children" : [ ]
} ,
{
"id" : 110102000000 ,
"pId" : 110100000000 ,
"name" : "西城区" ,
"pName" : "北京市" ,
"children" : [ ]
}
]
}
]