需要线确定树的层级机构,用levels表示,可以像下面这样处理,具体想要的数据结构看你需求再修改下
let levels = ['level1', 'level2', 'level3']
function arayToTree(arr, index){
index = index || 0
let result = [], obj = {}, props = levels[index]
if(!props || index == levels.length - 1){
return arr
}
arr.forEach(item => {
if(obj[item[props]]){
obj[item[props]].push(item)
}else{
obj[item[props]] = [item]
}
})
for(let k in obj){
result.push({
name: k,
child: arayToTree(obj[k], index + 1)
})
}
return result
}
let arr = [
{
level1: 'a1',
level2: 'b1',
level3: 'c1',
title: 'tt'
},{
level1: 'a1',
level2: 'b1',
level3: 'c2',
title: 'tt'
},{
level1: 'a2',
level2: 'b1',
level3: 'c1',
title: 'tt'
},{
level1: 'a2',
level2: 'b2',
level3: 'c1',
title: 'tt'
}
]
let data = arayToTree(arr)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…