一个json数组
var nodes = [
{"id":2,"title":"第一级1","parentid":0},
{"id":3,"title":"第二级1","parentid":2},
{"id":4,"title":"第二级2","parentid":2},
{"id":5,"title":"第三级1","parentid":4},
{"id":6,"title":"第三级2","parentid":3}
];
如何用递归的方式,转成如下树状格式:
var treeData = {
"id": "2",
"title": "第一级1",
"children": [
{
"id": "3",
"title": "第二级1",
"children": [
{
"id": "6",
"title": "第三级2",
"children": [
]
}
]
},
{
"id": "4",
"title": "第二级2",
"children": [
{
"id": "5",
"title": "第三级1",
"children": [
]
}
]
}
]
}
/**
* 数组转成树状结构
* @param data 数据结构 [{
"_parentId": 14,
"gmtCreate": "2019-01-15 09:44:38",
"gmtUpdate": "2019-01-15 09:44:38",
"id": 15,
"isShow": 1,
"name": "用户注册",
"orderIndex": 10000,
"parentId": 14
},...]
* @param pid 初始父节点id,一般是0
* @return [{
label: '一级 1',
children: [{
label: '二级 1-1',
children: [{
label: '三级 1-1-1'
}]
}]
}
*/
convertToTreeData(data, pid) {
const result = []
let temp = []
for (let i = 0; i < data.length; i++) {
if (data[i].parentId === pid) {
const obj = { 'title': data[i].name, 'id': data[i].id }
temp = this.convertToTreeData(data, data[i].id)
if (temp.length > 0) {
obj.children = temp
}
result.push(obj)
}
}
return result
}
使用方式:
var nodes = [
{"id":2,"title":"第一级1","parentid":0},
{"id":3,"title":"第二级1","parentid":2},
{"id":4,"title":"第二级2","parentid":2},
{"id":5,"title":"第三级1","parentid":4},
{"id":6,"title":"第三级2","parentid":3}
];
const treeData = convertToTreeData(nodes, 0)
console.log(treeData)