Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

递归 #577

Open
1922057635 opened this issue Aug 10, 2022 · 0 comments
Open

递归 #577

1922057635 opened this issue Aug 10, 2022 · 0 comments

Comments

@1922057635
Copy link

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)) 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant