使用reduce()+ arguments.callee() 方法实现不规则的多维数组扁平化

数组扁平化 是指将数组中不规则的多维数组去除维度,使其变成为一维数组。

// 转换前,需要扁平化的数组
const arr = [
    {
        id: 1,
        name: 'a',
        children: [
            {
                id: 11,
                name: 'a-c-1',
                children: [
                    {
                        id: 121,
                        name: 'a-c-2-1'
                    },
                    {
                        id: 122,
                        name: 'a-c-2-2',
                        children: [
                           {
                                id: 131,
                                name: 'a-c-3-1'
                           }
                        ]
                    }
                ]
            }
        ]
    },
    {
        id: 2,
        name: 'b',
        children: [
            {
                id: 21,
                name: 'b-c-1',
                children: [
                    {
                        id: 221,
                        name: 'b-c-2-1'
                    },
                    {
                        id: 222,
                        name: 'b-c-2-2',
                    }
                ]
            }
        ]
    },
]


const result = arr.reduce(function (prev, curr) {
    prev.push({
        id: curr.id,
        name: curr.name,
        parentId: curr.parentId,  // 第一维没有parentId,故parentId: undefined
        ref:curr // 原来的样子
    })
    curr.children && curr.children.forEach(v => {
        // 用于关联父级    
        v.parentId = curr.id
        // 再次调用当前作用域函数 function (prev, curr){}
        arguments.callee(prev, v) 
    })
    return prev
}, [])


console.log('转换前', JSON.stringify(arr, null, 4)) // 数据、不传、缩进(为整数时,表示每一级缩进的字符数)
console.log('转换后', result)


// JSON.stringify(value[, replacer [, space]])
// 参数:需要字符串化的对象、指定对象序列化过程中需要被处理的属性、指定输出字符串的缩进格式

不规则多维数组扁平化后的效果:

当然不规则多维数组扁平化的方法还有很多,如:

方法:flat()

使用:数组.flat(depth):newArray

该会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。 其中,depth指定要提取嵌套数组的结构深度,默认值为1。但使用 Infinity 作为深度,展开任意深度的嵌套数组。

flat()的实现详情见:https://www.cnblogs.com/vickylinj/p/14286298.html
树形数据转扁平化数组icon-default.png?t=N176http://【js数组reduce:树形数据转扁平化数组】 https://www.bilibili.com/video/BV1oW4y177Kv/?share_source=copy_web&vd_source=d50c6b3216dda73ea5961ad06d492fa2

猜你喜欢

转载自blog.csdn.net/qq_58062502/article/details/129034236
今日推荐