将一维数组处理成树形结构数据
作者:互联网
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 }
标签:findIndex,dealOptions,一维,pid,list,children,树形,数组,id 来源: https://www.cnblogs.com/grow-up-up/p/13215160.html