扁平数组转tree

2022-01-20  本文已影响0人  本萌妹

(function init() {

        let arr = [{

                id: 1,

                name: '部门1',

                pid: 0

            },

            {

                id: 2,

                name: '部门2',

                pid: 1

            },

            {

                id: 3,

                name: '部门3',

                pid: 1

            },

            {

                id: 4,

                name: '部门4',

                pid: 3

            },

            {

                id: 5,

                name: '部门5',

                pid: 4

            },

        ]

        const newArr = arr.reduce((total, item,index, list) => {

            if (item.pid === 0) {

                total.push({

                    ...item,

                    children: list.filter(f => f.pid === item.id)

                })

            } else {

                item.children = list.filter(f => f.pid === item.id)

            }

            return total

        }, [])

        console.log(newArr)

    })()

上一篇 下一篇

猜你喜欢

热点阅读