04-树形结构转数组/数组转树形结构/树形结构传入指定id找到所在那一项
树形结构转成(平铺)数组
var arr = [{ label: '一级 1', children: [{ label: '二级 1-1', children: [{ label: '三级 1-1-1' }] }] }, { label: '一级 2', children: [{ label: '二级 2-1', children: [{ label: '三级 2-1-1' }] }, { label: '二级 2-2', children: [{ label: '三级 2-2-1' }] }] }, { label: '一级 3', children: [{ label: '二级 3-1', children: [{ label: '三级 3-1-1' }] }, { label: '二级 3-2', children: [{ label: '三级 3-2-1' }] }] }] function becomeArr(arr){ let newArr = []; ~function fn(arr){ arr.forEach(item=>{ if(item.children && item.children.length > 0){ fn(item.children); } newArr.push({ label:item.label }) }) }(arr) return newArr; } let res = becomeArr(arr); console.log(res);
数组(有parentId)转树形结构
var arr = [ { id:'00', name:'公司' },{ id:'01', name:'一级部门', parentId:'00' },{ id:'02-1', name:'二级部门', parentId:'01' },{ id:'02-2', name:'二级部门', parentId:'01' },{ id:'03-1', name:'三级部门', parentId:'02-2' },{ id:'03-2', name:'三级部门', parentId:'02-2' }, ]; function becomeTree(arr){ let parArr = arr.filter(x=>!x.parentId); let sonArr = arr.filter(x=>x.parentId); function fn(par,son){ par.forEach(item=>{ son.forEach(x=>{ if(item.id === x.parentId){ fn([x],sonArr) if(!item.children){ item.children=[]; } item.children.push(x) } }) }) } fn(parArr,sonArr); return parArr; } let res = becomeTree(arr); console.log(res);
树形结构传入指定id找到所在那一项
var data = [{ id: 1, label: '一级 1', children: [{ id: 2, label: '二级 1-1', children: [{ id: 3, label: '三级 1-1-1' }] }] }, { id: 4, label: '一级 2', children: [{ id: 5, label: '二级 2-1', children: [{ id: 6, label: '三级 2-1-1' }] }, { id: 7, label: '二级 2-2', children: [{ id: 8, label: '三级 2-2-1' }] }] }, { id: 9, label: '一级 3', children: [{ id: 10, label: '二级 3-1', children: [{ id: 11, label: '三级 3-1-1' }] }, { id: 12, label: '二级 3-2', children: [{ id: 13, label: '三级 3-2-1' }] }] }] // 这里用找传入的指定id,返回传入的这个id所在的那个对象 function findObjFn(arr, id) { let temp = null; (function fn(arr, id) { arr.forEach(item => { if (item.id === id) { temp = item; } if (item.children && item.children.length > 0) { fn(item.children, id); } }) })(arr, id) return temp; } let res = findObjFn(data, 5) console.log(res);