Daily-Interview-Question icon indicating copy to clipboard operation
Daily-Interview-Question copied to clipboard

递归

Open 1922057635 opened this issue 3 years ago • 0 comments

let list = [ { id: 1, name: '部门A', parentId: 0 }, { id: 2, name: '部门B', parentId: 0 }, { id: 3, name: '部门C', parentId: 1 }, { id: 4, name: '部门D', parentId: 1 }, { id: 5, name: '部门E', parentId: 2 }, { id: 6, name: '部门F', parentId: 3 }, { id: 7, name: '部门G', parentId: 2 }, { id: 8, name: '部门H', parentId: 4 }, { id: 9, name: '部门I', parentId: 7 }, { id: 10, name: '部门J', parentId: 8 } ];

    function transform(data) {

        const findChildren = (data, id) => {
            return data.reduce((pre, cur) => {
                const temp = { ...cur }

                if (cur.parentId == id) {
                    const children = findChildren(data, cur.id)
                    if (children && children.length > 0) {
                        temp.children = children
                    }
                    pre.push(temp)
                }

                return pre
            }, [])
        }

        return data.reduce((pre, cur) => {
            if (!cur.parentId) {
                const children = findChildren(data, cur.id)
                pre.push({
                    ...cur,
                    children,
                })
            }
            return pre
        }, [])

    }

    console.log(transform(list)) 

1922057635 avatar Aug 10 '22 08:08 1922057635