递归遍历书树形数据获取父级key

结果

        var data = [
                {
                    "key": "sub1",
                    "children": [
                        {
                            "key": "sub1-1"
                        }
                    ]
                },
                {
                    "key": "sub2",
                    "children": [
                        {
                            "key": "sub2-1",
                            "children": [
                                {
                                    "key": "sub2-1-1"
                                },
                                {
                                    "key": "sub2-1-2"
                                },
                                {
                                    "key": "sub2-1-3",
                                    "children": [
                                        {
                                            "key": "sub2-1-3-1"
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "key": "sub2-2"
                        },
                        {
                            "key": "sub2-3"
                        }
                    ]
                },
                {
                    "key": "sub3",
                    "children": [
                        {
                            "key": "sub3-1"
                        },
                        {
                            "key": "sub3-2"
                        }
                    ]
                }
            ]
            const getopenkey = (arr, itme, reulit = []) => {
                arr.forEach((v) => {
                    if (itme.indexOf(v.key) !== -1) {
                        reulit.push(v.key);
                    }
                    if (v.children && v.children.length) {
                        getopenkey(v.children, itme, reulit)
                    }
                })
                return reulit
            }
            let element = 'sub2-1-3-1'
            console.log(getopenkey(data, element))

 

posted @ 2022-08-18 17:48  前端搬运工bug  阅读(61)  评论(0编辑  收藏  举报