数据结构如下
const data=[
{
"id": 60,
"name": "一级分类",
"icon": "/storage/images/2024/04/HEe1pPT2EecRgESMumVDh2MgenqB9JOr4MDQt83I.jpg",
"parent_id": 0,
"status": true,
"sort": 1,
"is_deleted": 0,
"children": [
{
"id": 61,
"name": "二级分类",
"icon": "fdsafdsa",
"parent_id": 60,
"status": true,
"sort": 1,
"is_deleted": 0,
"children": [
]
}
]
},
{
"id": 62,
"name": "范德",
"icon": "/storage/images/2024/04/HEe1pPT2EecRgESMumVDh2MgenqB9JOr4MDQt83I.jpg",
"parent_id": 0,
"status": true,
"sort": 1,
"is_deleted": 0,
"children": [
{
"id": 63,
"name": "法尔",
"icon": "fdsafdsa",
"parent_id": 62,
"status": true,
"sort": 1,
"is_deleted": 0,
"children": [
]
}
]
}
]
js代码如下
function findfamily(tree, itemId, path = []) {
for (const item of tree) {
if (item.id === itemId) {
// 找到目标项
return [...path, item];
}
if (item.children && item.children.length > 0) {
const result = findfamily(item.children, itemId, [...path, item]);
if (result) {
// 子树中找到目标项
return result;
}
}
}
// 未找到目标项
return null;
}
const result = findfamily(data, 63);