JavaScript之递归查找所有父节点

......

data: () => ({
  // 数据 dt: [{ id: '1', children: [ { id: '1-1', children: [ { id: '1-1-1', children: [] } ] }, { id: '1-2', children: [ { id: '1-2-1', children: [] } ] } ] }, { id: '2', children: [ { id: '2-1', children: [ { id: '2-1-1', children: [{ id: '2-1-1-1', children: [] }] } ] } ] }], path: [],// 保存递归到的每一层路径 curPath: [], // 当前路径 curId: '2-1-1', // 目标节点 isRecursion: true // 是否已找到目标几点 }), methods: { handleTestClick () { const { dt } = this this.path = [] dt.forEach((item, index) => { this.path[index] = [item.id] // 将每一层的路径保存下来 this.recursion(item.children, index) }) console.log(this.path, this.curPath) }, recursion (ary, index) { for (let i = 0; i < ary.length; i++) { const item = ary[i] this.isRecursion && this.path[index].push(item.id) // 将父节点id添加到当前层路径 if (this.curId === ary[i].id) { this.curPath = this.path[index] // index层的路径就是目标节点的路径 this.isRecursion = false break } if (item.children && item.children.length && this.isRecursion) { this.recursion(item.children, index) } } } }

......

  -- 经过地狱般的磨练,创造出天堂的力量。流过血的手指,弹出世间的绝唱!--

个人博客对应地址:http://www.devloper.top/article/detail/c8a20870-3329-11eb-8d80-e5b0e11d80e6