<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script>
let rootTree = {
childList: [
title: '1-1', id: 1, childList: [
title: '1-2', id: 2, childList: [
title: '1-3', id: 3, childList: [
title: '文件', id: 4
title: '2-1', id: 11, childList: [
title: '2-2', id: 111, childList: [
title: '2-3', id: 311, childList: [
title: '文件', id: 422
title: '3-1', id: 2222, childList: [
title: '3-2', id: 33333, childList: [
title: '3-3', id: 4444, childList: [
title: '文件', id: 5555
let xx = familyTree(rootTree, 422)
console.log(xx);
// 根据子元素返回他的所有父类
// 查找父节点
function familyTree (rootTree, id) {
let temp = []
let forFn = (treeItem, id) => {
// treeItem 精髓 - 传入者是一个对象.children结构,而且是作为目录节点,因为在子集childList里面找到以后
// 我们需要把父级的id进行一个存储,同时把父级的id继续递归,父-父级的childList里面找到以后
// 又会把父-父级的id进行存储,同时继续开启递归,直到顶层为空
for (let i = 0; i < treeItem.childList.length; i++) {
let item = treeItem.childList[i]
if (item.id === id) {
// 精髓 - 这边是返回父级的id
treeItem.id && temp.unshift({ title: treeItem.title, id: treeItem.id })
forFn(rootTree, treeItem.id)
break
} else {
if (item.childList?.length) {
// 精髓 - 这边通过children判断,但是传入的是item
forFn(item, id)
forFn(rootTree, id)
return temp
</script>