list 转换成tree
/**
* 将普通数组转换成tree
*/
listToTree (list, pid = 0) {
const tree = []
list.forEach(item => {
if (item.pid === pid) {
const children = this.listToTree(list, item.id)
if (children.length > 0) {
item.children = children
}
tree.push(item)
}
})
return tree
},
export const arrayToTree=({list=[], pid=0,parentIdKey="parentId",childrenKey='id'}={})=>{
const tree = []
list.forEach(item => {
console.log('item[parentIdKey]',item[parentIdKey],pid,item[parentIdKey] === pid)
if (item[parentIdKey] === pid) {
const children = arrayToTree({list, pid:item[childrenKey],parentIdKey,childrenKey})
if (children.length > 0) {
item.children = children
}
tree.push(item)
}
})
return tree
}
网友评论