首页 > 建站教程 > JS、jQ、TS >  js通过最后一级的ID反向查找所有的父级的ID正文

js通过最后一级的ID反向查找所有的父级的ID

递归


我爱模板网在工作中遇到了通过后端返回的ID,在js的多维数组中通过这个ID,反向查找所有的父级id,并将结果放在一个数组中:


假设有这么个数组:

var menu = [  //数组树型结构
    {
        childList:[],
        id:'11111'
    },
    {
        childList:[
            {
                childList:'',
                id:'22221'
            },
            {
                childList:[
                    {
                        childList:'',
                        id:'33332'
                    }
                ],
                id:'22222'
            }
        ],
        id:'11112'
    },
    {
        childList:[
            {
                childList:[
                    {
                        childList:[],
                        id:'33333'
                    }
                ],
                id:'22223'
            }
        ],
        id:'11113'
    },
    {
        childList:[
            {
                childList:[
                    {
                        childList:[
                            {
                                childList:[],
                                id:'44444'
                            }
                        ],
                        id:'33334'
                    }
                ],
                id:'22224'
            }
        ],
        id:'11114'
    },
]


假设最终查找的id数组为:

const openedKeys = []


假设后端返回的id为:

const lastOpenkey = '44444'


逆向递归查找方法:

function formTree(list, id) {
  list.forEach(item => {
    // 判断是否有children子集
    if (item.children && item.children.length) {
      // 判断子集里是否有想要的值来进行是否需要继续递归还是从头递归
      if (item.children.some(row => row.id === id)) {
        // 接收符合的数据id
        openedKeys.push(item.id)
        // 从头递归,找父级id
        formTree(menu, item.id)
      } else {
        // 没有找到,继续递归
        formTree(item.children, id)
      }
    } else return
  })
}


调用:

formTree(menu, lastOpenkey)