发布时间:2024-09-06 16:01
let data = [
{ id: 1, address: '安徽', parent_id: 0 },
{ id: 2, address: '江苏', parent_id: 0 },
{ id: 3, address: '合肥', parent_id: 1 },
{ id: 4, address: '庐阳区', parent_id: 3 },
{ id: 5, address: '大杨镇', parent_id: 4 },
{ id: 6, address: '南京', parent_id: 2 },
{ id: 7, address: '玄武区', parent_id: 6 },
{ id: 8, address: '梅园新村街道', parent_id: 7 },
{ id: 9, address: '上海', parent_id: 0 },
{ id: 10, address: '黄浦区', parent_id: 9 },
{ id: 11, address: '外滩', parent_id: 10 },
{ id: 12, address: '安庆', parent_id: 1 },
]
handleTree(data, pid) {
function tree(id) {
let arr = []
data
.filter((item) => {
return item.parent_id === id
})
.forEach((item) => {
arr.push({
area_id: item.id,
label: item.address,
children: tree(item.id),
})
})
return arr
}
return tree(pid)
}
console.log(handleTree(data, 0))
handleTree(data) {
// 删除 所有 children,以防止多次调用
data.forEach(function(item) {
delete item.children
})
// 将数据存储为 以 id 为 KEY 的 map 索引数据列
var map = {}
data.forEach(function(item) {
map[item.id] = item
})
// console.log(map);
var val = []
data.forEach(function(item) {
// 以当前遍历项,的parent_id,去map对象中找到索引的id
var parent = map[item.parent_id]
// 好绕啊,如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中
if (parent) {
;(parent.children || (parent.children = [])).push(item)
} else {
//如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级
val.push(item)
}
})
return val
},
console.log(handleTree(data, 0))
handleTree(arr) {
let cloneData = JSON.parse(JSON.stringify(arr)) // 对源数据深度克隆
return cloneData.filter((father) => {
let branchArr = cloneData.filter(
(child) => father.id == child.parent_id
) //返回每一项的子级数组
branchArr.length > 0 ? (father.children = branchArr) : '' //如果存在子级,则给父级添加一个children属性,并赋值
return father.parent_id == 0 //返回第一层
})
},
console.log(handleTree(data, 0))