You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript异步遍历数组全路径:多父组场景下代码失效求助

问题:获取多父组嵌套的所有路径(JavaScript + Axios)

我是JavaScript新手,现在想通过Axios的GET请求获取返回JSON对象的所有可能路径。每个项目可以属于一个或多个组,组之间还支持嵌套。

示例数据如下:

{"name": "item1","groupNames": [ "GROUPA" ]}

{"name": "GROUPA","groupNames": ["GROUPB"]}
....
{"name": "GROUPZ","groupNames": []}

现在遇到的问题是:我写的代码只能处理项目只有单个父组的情况,当项目有多个父组时(比如下面这个例子)就跑不起来了。

{"name": "item1","groupNames": [ "GROUPA","GROUPC","GROUPD" ]}
...

我当前的代码是这样的:

let parent = 'item1';
do{ 
  let endpoint = `${process.env.OPENHAB_HOST}:${process.env.OPENHAB_PORT}/rest/items/${parent}?recursive=false` 
  result = await getAxiosRequest(endpoint,{},res); // get request to specific endpoint
  parent = result.data.groupNames; 
} while(result.data.groupNames.length !== 0 )

解决方案:遍历所有分支路径

每个节点可能有多个父组,这本质是多叉树的遍历问题,需要用递归或队列处理所有分支,而不是单个节点循环。下面提供两种可行实现:

1. 深度优先遍历(递归)

适合收集所有完整路径,从item1一直到最顶层的空组:

// 存储所有完整路径
const allPaths = [];

// 递归函数:获取某节点的所有路径
async function fetchPath(currentNode, currentPath) {
  // 把当前节点加入路径
  const updatedPath = [...currentPath, currentNode];
  
  // 请求当前节点的父组信息
  const endpoint = `${process.env.OPENHAB_HOST}:${process.env.OPENHAB_PORT}/rest/items/${currentNode}?recursive=false`;
  const result = await getAxiosRequest(endpoint, {}, res);
  const parentGroups = result.data.groupNames;

  if (parentGroups.length === 0) {
    // 没有父组,这条路径走完了,存入结果
    allPaths.push(updatedPath);
    return;
  }

  // 遍历每个父组,递归继续获取路径
  for (const group of parentGroups) {
    await fetchPath(group, updatedPath);
  }
}

// 启动遍历,从item1开始
await fetchPath('item1', []);

// 输出所有路径
console.log(allPaths);

2. 广度优先遍历(队列)

适合层级遍历,同样能收集所有路径:

const allPaths = [];
// 队列存储当前节点和对应的路径
const queue = [{ node: 'item1', path: ['item1'] }];

while (queue.length > 0) {
  const { node, path } = queue.shift();
  
  const endpoint = `${process.env.OPENHAB_HOST}:${process.env.OPENHAB_PORT}/rest/items/${node}?recursive=false`;
  const result = await getAxiosRequest(endpoint, {}, res);
  const parentGroups = result.data.groupNames;

  if (parentGroups.length === 0) {
    allPaths.push(path);
    continue;
  }

  // 把每个父组加入队列,路径追加当前父组
  for (const group of parentGroups) {
    queue.push({
      node: group,
      path: [...path, group]
    });
  }
}

console.log(allPaths);

原代码失效原因

原代码每次把parent设为整个groupNames数组,下次循环会用数组拼接接口地址(比如/items/GROUPA,GROUPC,GROUPD),不符合接口要求;同时这种方式也无法追踪每条独立的路径分支。

内容的提问来源于stack exchange,提问作者Θοδωρής Σουλτανόπουλος

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:40:21