js递归对象中存在两个数组

const data: any = {
  type: 'root',
  id: GenNonDuplicateID(),
  children: [
    {
      type: 'approval',
      id: GenNonDuplicateID(),
      branch: [
        {
          type: 'branch',
          id: GenNonDuplicateID(),
          children: [],
        },
        {
          type: 'branch',
          id: GenNonDuplicateID(),
          children: [],
        },
      ],
      children: [
        {
          type: 'write',
          id: GenNonDuplicateID(),
          children: []
        }
      ]
    },
  ],
};

如何在这类数据中递归查询,children中可能会存在branch

该回答引用ChatGPT
请参考下面的解决方案,如果有帮助,还请点击 “采纳” 感谢支持!
可以使用递归算法来在这样的数据中进行查询。具体实现可以使用函数,该函数接收两个参数:一个是要查询的对象,另一个是要查询的类型。

在函数内部,遍历该对象的所有子元素,如果该子元素的类型与查询的类型匹配,则返回该元素;否则,递归调用该函数,并对该子元素进行查询。

function findType(obj, type) {
  if (obj.type === type) {
    return obj;
  }
  for (const child of obj.children) {
    const result = findType(child, type);
    if (result) {
      return result;
    }
  }
  return null;
}

const result = findType(data, 'write');
console.log(result);


递归 遍历不行吗

需要达到什么结果,存在branch取出?