Js 树结构 同级树内去重

有时候后端返回的树结构存在同名的情况,前端可以通过遍历,将同一级别树下的重名去掉

function reTree(tree) {
    let res = []
    let arr = []

    tree.forEach((item) => {

        if (arr.includes(item.name))
            return
        arr.push(item.name)
        
        let children = []
        
        if (item.children)
            children = reTree(item.children)

        let temp = {
            ...item,
            children
        }

        res.push(temp)
    })

    return res
}

let data = [
    {
        name: '1',
        children: [
            { name: '1-1' }
        ]
    },
    {
        name: '1',
        children: [
            { name: '1-1' }
        ]
    },
    {
        name: '2',
        children: [
            {
                name: '1-1',
                children: [
                    {
                        name: '1-1-1'
                    }
                ]
            },
            {
                name: '1-1',
                children: [
                    {
                        name: '1-1-2'
                    }
                ]
            },
               {
                name: '1-2',
                children: [
                    {
                        name: '1-1-2'
                    }
                ]
            },
        ]
    }
]

你可能感兴趣的:(js,数据结构,javascript,数据结构)