简单的树状结构遍历方法
cv方法
// 方法
function handleTree(data, deptid, parentid, children, rootid) {
deptid = deptid || "deptid"
parentid = parentid || 'parentid'
children = children || 'children'
if (data.length == 0) {
return
}
//console.log(data.map(item => return item[parentId] }))
if (typeof (data[0][parentid]) == 'string') {
rootid = data[0][parentid]
console.log(rootid);
} else {
rootid = 0
}
//rootid = rootid ll Math.min.apply(Math, data.map(item( return item[parentId] )) Il "e
//对源数据深度克隆
const cloneData = JSON.parse(JSON.stringify(data))
//循环所有项
const treeData = cloneData.filter(father => {
let branchArr = cloneData.filter(child => { //返回每一项的子级数组
return father[deptid] === child[parentid]
console.log(cloneData);
})
branchArr.length > 0 ? father.children = branchArr : '';//返回第一层
return father[parentid] === rootid;
})
return treeData != '' ? treeData : data;
}
使用
// 示例数组
let arr = [
{ ids: 1,parentid:0, text: '父1' },
{ ids:3,parentid: 1, text: '子1' },
{ ids:4,parentid: 1, text: '子1' },
{ ids:5,parentid: 1, text: '子1' },
{ ids: 2,parentid:0, text: '父1' },
{ ids:3,parentid: 2, text: '子1' },
{ ids:4,parentid: 2, text: '子1' },
{ ids:5,parentid: 2, text: '子1' },
]
let arr2=handleTree(arr,"ids","parentid")
console.log(arr2);
返回结果