<!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="css/style.css" rel="stylesheet"> </head> <body> <script> let list = [{ "id": 1, "title": "首页", "parentId": 0, }, { "id": 3, "title": "权限管理", "parentId": 2, }, { "id": 4, "title": "页面管理", "parentId": 3, }, { "id": 5, "title": "适用组件", "parentId": 0, }, { "id": 6, "title": "json编辑器", "parentId": 5, }, { "id": 7, "title": "富文本编辑器", "parentId": 5, }, { "id": 2, "title": "系统管理", "parentId": 0, }, { id: 8, "title": "组件管理", "parentId": 4 } ] function setTree(list) { return list.filter((item) => { let children = list.filter((child) => { return item.id == child.parentId }) if (children.length > 0) { item['children'] = children } return item['parentId'] == 0 }) } console.log(setTree(list)); </script> </body> </html>
转换前
转换后
标签:title,树结构,list,children,item,扁平,数组,parentId,id From: https://www.cnblogs.com/jzm2842688813/p/16838065.html