<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <script> var menuArry = [ { id: 1, name: "办公管理", pid: 0 }, { id: 2, name: "请假申请", pid: 1 }, { id: 3, name: "出差申请", pid: 1 }, { id: 4, name: "请假记录", pid: 2 }, { id: 5, name: "系统设置", pid: 0 }, { id: 6, name: "权限管理", pid: 5 }, { id: 7, name: "用户角色", pid: 6 }, { id: 8, name: "菜单设置", pid: 6 }, ]; var getJsonTree = function (data, parentId) { var itemArr = []; for (var i = 0; i < data.length; i++) { var node = data[i]; if (node.pid === parentId) { var newNode = { id: node.id, title: node.name, children: getJsonTree(data, node.id), }; itemArr.push(newNode); } } return itemArr; }; console.log(getJsonTree(menuArry, 0)); </script> </body> </html>
标签:node,name,递归,pid,js,转树,var,data,id From: https://www.cnblogs.com/7-up/p/17429547.html