Use the reduce()+arguments.callee() method to achieve irregular multidimensional array flattening

Array flattening refers to removing the dimensions of the irregular multi-dimensional array in the array to make it a one-dimensional array.

// 转换前,需要扁平化的数组
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]])
// 参数:需要字符串化的对象、指定对象序列化过程中需要被处理的属性、指定输出字符串的缩进格式

The effect of flattening the irregular multidimensional array:

Of course, there are many ways to flatten irregular multidimensional arrays, such as:

Method: flat()

Use: array.flat( depth):newArray

This will recursively traverse the array according to a specified depth, and combine all elements and elements in the traversed sub-array into a new array and return. Among them, depthspecify the depth of the structure to extract the nested array, the default value is 1. But using  Infinity as-depth, unwraps nested arrays of arbitrary depth.

For details on the implementation of flat(), see: https://www.cnblogs.com/vickylinj/p/14286298.html
Convert tree data to flat array icon-default.png?t=N176http://[js array reduce: tree data to flat array] https ://www.bilibili.com/video/BV1oW4y177Kv/?share_source=copy_web&vd_source=d50c6b3216dda73ea5961ad06d492fa2

Guess you like

Origin blog.csdn.net/qq_58062502/article/details/129034236