树状结构扁平化

/**
 * @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 } ]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。