将一维数组处理成树形结构数据
list是个一维数组数据,每项数据中有id和pid,id是自己的唯一标识符,pid是自己父级的id。
1 let list = [ 2 {name:"1",id:"1"}, 3 {name:"1-1",id:"1-1",pid:"1"}, 4 {name:"1-1-1",id:"1-1-1",pid:"1-1"}, 5 {name:"2",id:"2"}, 6 {name:"2-1",id:"2-1",pid:"2"} 7 ]
1 function dealOptions(list){ 2 let dealOptions = [] 3 // 给每个数据加children属性 4 list.forEach( one => { 5 one.children = [] 6 }) 7 list.forEach( one => { 8 let findIndex = list.findIndex(item => { 9 return item.id === one.pid 10 }) 11 if ((!one.pid && one.pid !== 0 && one.pid !== false) || findIndex === -1) { 12 dealOptions.push(one) 13 } else { 14 list[findIndex].children.push(one) 15 } 16 }) 17 return dealOptions 18 }