const arr1 = [ { menuId: 1, name: "系统管理1", parentMenu: null, }, { menuId: 2, name: "系统管理2", parentMenu: null, }, { menuId: 3, name: "系统管理1_0", parentMenu: 1, }, { menuId: 4, name: "系统管理1_1", parentMenu: 1, }, { menuId: 5, name: "系统管理2_0", parentMenu: 2, }, { menuId: 6, name: "系统管理2_2_0", parentMenu: 5, }, { menuId: 7, name: "系统管理3", parentMenu: null, }, { menuId: 8, name: "系统管理1-1-2", parentMenu: 4, }, ]; const arr2 = [ { id: 1, name: "1", parentId: null, }, { id: 2, name: "2", parentId: null, }, { id: 3, name: "1_0", parentId: 1, }, ]; function toTree2(arr, Id='id', parentId='parentId', children='children') { // 先copy一份数据 let newA=JSON.parse(JSON.stringify(arr)); return newA.filter(p=>{ //遍历 const c = newA.filter(item=>item[parentId]==p[Id]); //找到就赋值 c.length && (p[children] = c) return p[parentId]==null }) } const resultArr = toTree2(arr1,'menuId','parentMenu','list'); const resultArr1 = toTree2(arr2); arr1[6].name='hedan'; console.log('树形结构', resultArr1);
标签:系统管理,name,parentMenu,menuId,javascript,树形,parentId,手写,null From: https://www.cnblogs.com/ddqyc/p/16955196.html