- 已知数组[[1,2,3], [1,5,6], [1, 7, 10]]
- 转换成
[{
id: 1,
children: [{
id: 2,
children: [{
id: 3
}]
}, {
id: 5,
children: [{
id: 6
}]
}, {
id: 7,
children: [{
id: 10
}]
}]
}]
const concertTree = (arr) => {
// 存放tree数据
let result = [];
arr.forEach(item => {
// 每次新的遍历重新获取result值
let temp = result;
item.forEach(childId => {
// 判断当前的数字是否在temp结构第一层
const dist = temp.findIndex(c => c.id === childId) ?? -1
// 如果不存在,创建新的push进去,并把temp重新赋值
if(dist === -1){
temp.push({
id: childId,
children: []
})
temp = temp.at(-1)['children']
} else {
temp = temp[dist]['children']
}
})
})
return result
}