js将数据转为菜单,一个for?
let data = [ { id: '02', lable: '产品leader', pid: '01' }, { id: '03', lable: 'UIleader', pid: '01' }, { id: '07', lable: '产品经理', pid: '02' }, { id: '04', lable: '技术leader', pid: '01' }, { id: '21', lable: '技术leader2', pid: '20' }, { id: '05', lable: '测试leader', pid: '01' }, { id: '06', lable: '运维leader', pid: '01' }, { id: '08', lable: '产品经理', pid: '02' }, { id: '09', lable: 'UI设计师', pid: '03' }, { id: '10', lable: '前端工程师', pid: '04' }, { id: '11', lable: '后端工程师', pid: '04' }, { id: '12', lable: '后端工程师', pid: '04' }, { id: '13', lable: '测试工程师', pid: '05' }, { id: '14', lable: '测试工程师', pid: '05' }, { id: '15', lable: '运维工程师', pid: '06' }, { id: '01', lable: '项目经理', pid: '' }, { id: '20', lable: '项目经理22', pid: '' }, ] data.sort(_ => Math.random() - 0.5) //乱序
/**
* 利用浅拷贝
*/ function toData2(arr) { let obj = {}, result = []; for (let index = 0; index < arr.length; index++) { const element = arr[index]; if (!obj[element.id]) { obj[element.id] = element obj[element.id].children = [] } if (element.pid && !obj[element.pid]) { obj[element.pid] = { children: [] } } if (!element.pid) { element.children = obj[element.id].children result.push(element) } else { obj[element.pid].children.push(element) } } return result } function toData3(arr) { let obj = {}, result = []; arr.forEach(element => { if (!obj[element.id]) { obj[element.id] = element obj[element.id].children = [] } if (element.pid && !obj[element.pid]) { obj[element.pid] = { children: [] } } if (!element.pid) { element.children = obj[element.id].children result.push(element) } else { obj[element.pid].children.push(element) } }) return result } console.time('toData2') console.log(JSON.stringify(toData2(data))) console.timeEnd('toData2') console.time('toData3') console.log(JSON.stringify(toData3(data))) console.timeEnd('toData3')