js 遍历所有的数据,查出来匹配的元素,被遍历的数据包含多层children

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.');
}

  

posted @ 2024-11-26 14:51  世界我快乐  阅读(145)  评论(0)    收藏  举报