介绍
最近笔试遇到一个题是要求将平铺节点数组转嵌套树,一眼看上去挺简单的,当时花了几分钟写了个很low方法,只能勉强实现功能。试后网上查了下,有更好的方法,自己又实现了一遍,记录下。
代码
// 输入数据
const TEST_DATA = [
{ title: '1', depth: 1 },
{ title: '1-1', depth: 2 },
{ title: '1-1-1', depth: 3 },
{ title: '1-1-2', depth: 3 },
{ title: '1-2', depth: 2 },
{ title: '2', depth: 1 },
{ title: '2-1', depth: 2 }
]
/**
* 平铺节点数组转嵌套树
* @param {Array} data
*/
const renderTreeDom = (data) => {
const result = []
const treeDom = {}
data.forEach(item => {
treeDom[item.title] = item
})
Object.keys(treeDom).forEach(key => {
if (key.split('-').length > 1) {
if (!treeDom[key.split('-').slice(0, -1).join('-')].children) {
treeDom[key.split('-').slice(0, -1).join('-')].children = []
}
treeDom[key.split('-').slice(0, -1).join('-')].children.push(treeDom[key])
} else {
result.push(treeDom[key])
}
})
return result
}
console.log(renderTreeDom (TEST_DATA ))
// 输出结果
[
{
"title": "1",
"depth": 1,
"children": [
{
"title": "1-1",
"depth": 2,
"children": [
{
"title": "1-1-1",
"depth": 3
},
{
"title": "1-1-2",
"depth": 3
}
]
},
{
"title": "1-2",
"depth": 2
}
]
},
{
"title": "2",
"depth": 1,
"children": [
{
"title": "2-1",
"depth": 2
}
]
}
]
总结
考点应该有string和array的常用函数、object的浅拷贝等。这个方法应该还能改进,也希望批评指导。