const data = [
{
id: 1,
parentId: 0,
title: "0-1"
},
{
id: 2,
parentId: 0,
title: "0-2"
},
{
id: 11,
parentId: 1,
title: "1-1"
},
{
id: 12,
parentId: 1,
title: "1-2"
},
{
id: 21,
parentId: 2,
title: "2-1"
}]
const generateTree = (list,
rootId,
{ idName = 'id', parentIdName = 'parentId', childName = 'children' } = {}
) => {
if (!Array.isArray(list)) {
return list
}
const objMap = {}
const result = []
for (const item of list) {
const id = item[idName]
const parentId = item[parentIdName]
objMap[id] = !objMap[id] ? item : { ...item, ...objMap[id] }
const treeItem = objMap[id]
if (parentId === rootId) {
result.push(treeItem)
} else {
if (!objMap[parentId]) { objMap[parentId] = {} }
if (!objMap[parentId][childName]) {
objMap[parentId][childName] = []
}
objMap[parentId][childName].push(treeItem)
}
}
return result
}
const result = generateTree(data, 0)
console.log(result)