const generateTree = (data, parentId, { idName = 'id', parentIdName = 'parentId', childName = 'children' } = {}) => {
if (!Array.isArray(data)) {
console.warn('只支持传入数组')
return data
}
return data.reduce((prev, curt) => {
if (curt[parentIdName] === parentId) {
const children = generateTree(data, curt[idName])
console.log(curt)
if (children?.length) {
curt[childName] = children
}
return [...prev, curt]
}
return prev
}, [])
}
const fn = arr => {
const res = []
const map = arr.reduce((res, item) => ((res[item.id] = item), res), {})
for (const item of Object.values(map)) {
if (!item.pId) {
res.push(item)
} else {
const parent = map[item.pId]
parent.child = parent.child || []
parent.child.push(item)
}
}
return res
}
const flatArr = [
{ 'id': '001', 'name': '节点1' },
{ 'id': '0011', 'parentId': '001', 'name': '节点1-1' },
{ 'id': '00111', 'parentId': '0011', 'name': '节点1-1-1' },
{ 'id': '002', 'name': '节点2' }
]
generateTree(flatArr)
const flatTree = (data, childName = 'children') => {
if (!Array.isArray(data)) {
console.warn('只支持传入数组')
return []
}
return data.reduce((prev, curt) => {
const childs = curt[childName]?.length ? flatTree(curt[childName]) : []
return [...prev, curt, ...childs]
}, [])
}
console