扁平数据变为嵌套数据
<!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 data = [ { id: 2, pid: 0, title: "课程管理" }, { id: 7, pid: 0, title: "课程管理" }, { id:3, pid: 2, title: "课程操作" }, { id:4, pid: 2, title: "课程数据" }, { id:5, pid: 6, title: "课程数据2" }, ] console.log(formaDataree(data)) function formaDataree(data) { let parents = data.filter( p => p.pid === 0), children = data.filter(c => c.pid !== 0); dataToTree(parents, children); return parents; function dataToTree(parents, children) { parents.map(p => { children.map((c,i) => { if(p.id === c.pid) { let _children = JSON.parse(JSON.stringify(children)); _children.splice(i, 1); dataToTree([c], _children); if(p.children) { p.children.push(c) } else { p.children = [c]; } } }) }) } } </script> </body> </html>