首先让我们看一组树形结构数据
const tree = [
{
id: 1,
name: 'a',
children: [
{
id: 12,
name: 'aa',
children: [
{
id: 121,
name: 'aaa',
},
{
id: 122,
name: 'aab'
}
]
}
]
},
{
id: 2,
name: 'b'
},
{
id: 3,
name: 'c',
children: [
{
id: 31,
name: 'cc',
children: [
{
id: 311,
name: 'ccc'
}
]
}
]
}
]
方法:
const result = tree.reduce(function fn(prev: any, curr: any) {
curr.parentId ? prev.push({
id: curr.id,
name: curr.name,
parentId: curr.parentId
}) : prev.push({
id: curr.id,
name: curr.name
})
curr.children && curr.children.forEach((item: any) => {
item.parentId = curr.id
fn(prev, item)
})
return prev
}, [])