<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>无限分类</title> </head> <body> <script> window.onload = function () { console.log(deeploop(0)); }; /** * 根据 id 查询到数据并将数据存储到数组 返回 */ var findById = function (id) { let child = []; arr.forEach((value) => { if (value.pid == id) { child.push(value); } }); return child; }; /** * 递归查询 到数据并将数据存储到数组 返回 */ var deeploop = function (id) { let dataArr = findById(id); if (dataArr.length <= 0) { return null; } else { dataArr.forEach((value) => { if (deeploop(value.id) != null) { value["children"] = deeploop(value.id); } }); } return dataArr; }; /** * 每一个分类都有记录它的父级id (pid 意为 parent id) * 当为顶级分类时,它的父级id为0 */ var arr = [ { id: 1, name: "计算机专业", pid: 0 }, { id: 2, name: "软件专业", pid: 1 }, { id: 3, name: "前端", pid: 2 }, { id: 33, name: "html", pid: 3 }, { id: 34, name: "css", pid: 3 }, { id: 4, name: "后端", pid: 2 }, { id: 41, name: "php", pid: 4 }, { id: 42, name: "java", pid: 4 }, { id: 5, name: "动漫专业", pid: 0 }, { id: 51, name: "2d动漫", pid: 5 }, { id: 511, name: "插画设计", pid: 51 }, { id: 52, name: "3d动漫", pid: 5 }, ]; </script> </body> </html>