list是个一维数组数据,每项数据中有id和pid,id是自己的唯一标识符,pid是自己父级的id。
1 function(list){ 2 let dealOptions = [] 3 // 给每个数据加children属性 4 _.forEach(list, one => { 5 one.children = [] 6 }) 7 _.forEach(list, one => { 8 let findIndex = _.findIndex(list, 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 }