一、效果:
将
treeRawData:[
//后端返回的数据
{ title: "地球", id: "1", parentId: "0" },
{ title: "中国", id: "2", parentId: "1" },
{ title: "上海", id: "3", parentId: "2" },
{ title: "徐汇", id: "4", parentId: "3" },
{ title: "美国", id: "5", parentId: "1" },
{ title: "纽约", id: "6", parentId: "5" },
]
转化为
treeData:[
//前端处理后的数据
{
title: "地球",
id: "1",
children: [
{
title: "中国",
id: "2",
children: [
{
title: "上海",
id: "3",
children: [
{
title: "徐汇",
id: "4",
},
],
},
],
},
{
title: "美国",
id: "5",
children: [
{
title: "纽约",
id: "6",
},
],
},
],
},
]
二、js代码:
//将后端返回的list数据转化为树结构
export const listToTree = (list) => {
var arr = []
let items = {}
var idsStr = ''
// 获取每个节点的直属子节点(是直属,不是所有子节点)
for (let i = 0; i < list.length; i++) {
let key = list[i].parentId
if (items[key]) {
items[key].push(list[i])
} else {
items[key] = []
items[key].push(list[i])
}
idsStr += idsStr === '' ? list[i].id : ',' + list[i].id
}
for (var key in items) {
if (idsStr.indexOf(key) === -1) {//找到最大的父节点key
arr=formatTree(items, key)
}
}
console.log(arr)
return arr
}
function formatTree(items, parentId) {
let result = []
if (!items[parentId]) {
return result
}
for (let t of items[parentId]) {
t.children = formatTree(items, t.id)//递归获取children
result.push(t)
}
return result
}
三、在vue文件中引用:
import { listToTree } from "../../../libs/listToTree.js";
this.treeData = listToTree(this.treeRawData); //将后端返回的list数据转化为树结构