目录
1、实现代码
- 1、实现代码
- 2、相关链接
let arrData = [ { id: 1, pid: 0, name: "全部", }, { id: 2, pid: 1, name: "药食同源", }, { id: 3, pid: 2, name: "特殊食品", }, { id: 4, pid: 2, name: "进口食品", }, { id: 5, pid: 4, name: "新资源食品", }, { id: 6, pid: 1, name: "绿色有机", }, { id: 7, pid: 3, name: "食品检验检测", }, { id: 8, pid: 3, name: "标签审核", }, { id: 9, pid: 5, name: "法律服务", }, ]; function arrayToTree(arr) { // 定义result:存储最终结果 // 定义itemMap:存储分类后的结果 let result = [], itemMap = {}; for (let item of arr) { // 每一次循环取出对应的id和pid let id = item.id, pid = item.pid; // 如果itemMap对象中没有对应id // 就创建一个新的对象 if (!itemMap[id]) { itemMap[id] = { children: [], }; } itemMap[id] = { ...item, children: itemMap[id]['children'] }; let treeItem = itemMap[id]; if (pid === 0) { result.push(treeItem); } else { if (!itemMap[pid]) { itemMap[pid] = { children: [], }; } itemMap[pid].children.push(treeItem); } } return result; } console.log('arrayToTree:', arrayToTree(arrData));2、相关链接
掘金-面试了十几个高级前端,竟然连(扁平数据结构转Tree)都写不出来