大叫好,今天书写了一个扁型转换为树型的例子,使用的是递归,请大家食用,无毒
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>树结构</title> </head> <body> <script> let arr = [{ id: 1, name: "中国", pid: 0 }, { id: 78, name: "美国", pid: 0 }, { id: 2, name: "河南", pid: 1 }, { id: 3, name: "河北", pid: 1 }, { id: 4, name: "新乡", pid: 2 }, { id: 5, name: "开封", pid: 2 }, { id: 6, name: "许昌", pid: 2 }, { id: 7, name: "漯河", pid: 2 }, { id: 8, name: "石家庄", pid: 3 }, { id: 9, name: "邢台", pid: 3 }, { id: 10, name: "秦皇岛", pid: 3 }, { id: 11, name: "衡水", pid: 3 }, { id: 12, name: "延津县", pid: 4 }, { id: 13, name: "封丘县", pid: 4 }, { id: 14, name: "长垣县", pid: 4 }, { id: 15, name: "王楼镇", pid: 12 }, { id: 16, name: "牛屯镇", pid: 12 }, { id: 17, name: "王屯镇", pid: 12 }, { id: 18, name: "刘庄乡", pid: 15 }, { id: 19, name: "王庄乡", pid: 15 }, { id: 20, name: "陈庄乡", pid: 15 }, { id: 21, name: "娄庄乡", pid: 15 }, { id: 22, name: "张庄乡", pid: 15 }, { id: 23, name: "李庄乡", pid: 15 }, { id: 24, name: "草庄乡", pid: 15 }, { id: 25, name: "刘庄村", pid: 18 }, { id: 26, name: "王庄村", pid: 18 }, { id: 27, name: "李庄村", pid: 18 }, { id: 28, name: "和庄村", pid: 18 }]; // 递归函数构建树结构 function buildTree(arr, pid) { let result = []; for (let i = 0; i < arr.length; i++) { if (arr[i].pid === pid) { let children = buildTree(arr, arr[i].id); if (children.length) { arr[i].children = children; } result.push(arr[i]); } } return result; } // 构建树结构 let tree = buildTree(arr, 0); console.log(tree); </script> </body> </html>
请大家看完之后给我点个关注,谢谢您了