首页 > 其他分享 >递归遍历书树形数据获取父级key

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

时间:2022-08-18 17:56:41浏览次数:50  
标签:reulit 遍历 sub2 sub3 父级 getopenkey key children

结果

        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))

 

标签:reulit,遍历,sub2,sub3,父级,getopenkey,key,children
From: https://www.cnblogs.com/zxh-bug/p/16599592.html

相关文章