/**
* @description 树状数组扁平化
* @param { Array } tree 树状结构数组
* @param { Array } arr 扁平化后的数组
* @param { String } childrenKey 子节点键名
* @return { Array } 扁平化后的数组
*/
export function flatten(tree = [], arr = [], childrenKey = 'children') {
tree.forEach((item) => {
const children = item[childrenKey]
children ? flatten(children, arr, childrenKey) : arr.push(item)
})
return arr
}
// 例如有该树状数据
treeData: [
{
childrenData: [
{
name: "aaa",
cid: 2,
},
],
},
{
childrenData: [
{
childrenData: [
{
name: "bbb",
cid: 3,
},
],
},
],
},
{
name: "ccc",
cid: 1
},
],
this.treeFlatten = flatten(this.treeData, [], 'childrenData')
console.log(this.treeFlatten)
[ { "name": "aaa", "cid": 2 }, { "name": "bbb", "cid": 3 }, { "name": "ccc", "cid": 1 } ]
网友评论