Skip to main content

Tree 转扁平数据

Tree 数据:

 const treeData = [{
id: 1,
label: 'Level one 1',
type: 1,
children: [{
id: 4,
label: 'Level two 1-1',
type: 2,
children: [{
id: 9,
label: 'Level three 1-1-1',
type: 3
}, {
id: 10,
label: 'Level three 1-1-2',
type: 3
}]
}, {
id: 11,
label: 'Level three 1-2',
type: 2,
children: [{
id: 12,
label: 'Level three 1-2-1',
type: 3
}, {
id: 13,
label: 'Level three 1-2-2',
type: 3
}, {
id: 14,
label: 'Level three 1-2-3',
type: 3
}, {
id: 15,
label: 'Level three 1-2-4',
type: 3
}]
}]
}]

输出结果:

[
0: {id: 9, label: 'Level three 1-1-1', type: 3}
1: {id: 10, label: 'Level three 1-1-2', type: 3}
2: {id: 12, label: 'Level three 1-2-1', type: 3}
3: {id: 13, label: 'Level three 1-2-2', type: 3}
4: {id: 14, label: 'Level three 1-2-3', type: 3}
5: {id: 15, label: 'Level three 1-2-4', type: 3}
]

递归

思路:

  1. 声明 res
  2. 遍历获取每项子集const { children, ...i } = item
  3. 如果 children 存在,使用concant递归连接
  4. 不存在则存入 i
 const treeToList = (list) => {
let res = []
for(const item of list ){
const { children, ...i } = item
if(children && children.length){
res = res.concat(treeToList(children))
}else{
res.push(i)
}
}
return res
}

使用方法:

 //查看数据是否转换成功
const treeList = treeToList(treeData)
console.log('树状结构转扁平结构', treeList)