扁平数组树状化(利用递归,两个函数完成树状转化 )
数组格式:
let list = [
{ id: 1, title: '标题1', p_id: 0 },
{ id: 2, title: '标题2', p_id: 0 },
{ id: 3, title: '标题2-1', p_id: 2 },
{ id: 4, title: '标题2-2', p_id: 2 },
{ id: 5, title: '标题2-2-1', p_id: 4 },
{ id: 6, title: '标题2-2-1-1', p_id: 5 },
{ id: 7, title: '标题2-2-1-2', p_id: 5 },
]
function getTree (arr) {
const treeData = []
arr.forEach(v => {
//找到第一层父节点
if (v.p_id === 0) {
treeData.push(v)
v.children = getChildren(arr, v.id)
}
})
return treeData
}
function getChildren (arr, id) {
const children = []
//查找父节点对应的子节点
arr.forEach(v => {
if (v.p_id === id) {
v.children = getChildren(arr, v.id)
children.push(v)
}
})
return children
}
console.log(getTree(list))//打印输出结果
树状数组扁平化
直接利用上面转化结果进行扁平化
//树状扁平化
function flatten (data) {
return data.reduce((pre, cur) => {
const { id, title, p_id, children = [] } = cur
return pre.concat([{ id, title, p_id }], flatten(children))
}, [])
}
console.log(flatten(fu(list)))