function findNodeById(data, id) {
for (const item of data) {
if (item.id === id) {
return item; // 找到匹配的节点,直接返回
}
if (item.children && item.children.length > 0) {
const found = findNodeById(item.children, id); // 递归查找子节点
if (found) {
return found; // 在子节点中找到匹配的节点,返回
}
}
}
return null; // 没有找到匹配的节点,返回 null
}
// 使用示例
const targetId = 3;
const foundNode = findNodeById(data, targetId);
if (foundNode) {
console.log('Found node:', foundNode);
} else {
console.log('Node with id', targetId, 'not found.');
}