要在一个多维数组中循环遍历 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('未找到节点');
}