要在一個多維數組中循環遍歷 children,并在找到具有特定 id 的節點后,獲取從根節點到該節點路徑上每一級(包括自身)的 name 值,你可以使用遞歸函數,并在遞歸的過程中收集這些 name 值。
const data = [
{
id: 1,
name: 'Root',
children: [
{
id: 2,
name: 'Level 1 - A',
children: [
{
id: 3,
name: 'Level 2 - A1',
// 其他屬性...
children: [
// 更深層次的子節點...
]
},
// 其他子節點...
],
},
{
id: 4,
name: 'Level 1 - B',
// 無子節點或更多子節點...
},
// 其他子節點...
],
},
// 其他根節點...
];
function findPathNamesById(nodes, targetId, pathNames = []) {
for (let node of nodes) {
// 將當前節點的 name 添加到路徑中
const newPath = [...pathNames, node.name];
if (node.id === targetId) {
return newPath; // 找到目標節點,返回完整的路徑名稱數組
}
if (node.children && node.children.length > 0) {
// 遞歸查找子節點
const result = findPathNamesById(node.children, targetId, newPath);
if (result) {
return result; // 在子節點中找到目標節點,返回完整的路徑名稱數組
}
}
}
return null; // 沒有找到目標節點,返回 null
}
// 使用示例
const targetId = 3;
const pathNames = findPathNamesById(data, targetId);
if (pathNames) {
console.log('從根到目標節點的名稱路徑:', pathNames.join(' -> '));
// 輸出: 從根到目標節點的名稱路徑: Root -> Level 1 - A -> Level 2 - A1
} else {
console.log('未找到節點');
}