我想的应该是有6项,但是它只push了4项,有子集的父项没进去
export function flatten (tree = [], arr = [], childrenKey = 'children') {
tree.forEach((item) => {
const children = item[childrenKey]
children ? flatten(children, arr, childrenKey) : arr.push(item)
})
return arr
}
const treeData = [
{ key: '0-0', title: '0-0' },
{
key: '0-1',
title: '0-1',
children: [
{ key: '0-1-0', title: '0-1-0' },
{
key: '0-2-0',
title: '0-2-0',
children: [
{ key: '0-2-1', title: '0-2-1' },
{ key: '0-2-2', title: '0-2-2' }
]
}
]
}
]
// 调用
this.tableData = flattensFunc(treeData, [], 'children')
// 输出
[
{
"key": "0-0",
"title": "0-0"
},
{
"key": "0-1-0",
"title": "0-1-0"
},
{
"key": "0-2-1",
"title": "0-2-1"
},
{
"key": "0-2-2",
"title": "0-2-2"
}
]
不管有没有 children,当前项都需要 push 啊,然后再说,有子集的递归进去
对于带 children 的 item,输出会含
children
属性,如果不需要,可以用新对象来过滤掉