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

嵌套JSON生成带完整组路径的名称列表问题求助

解决嵌套JSON中提取带完整组路径的名称列表问题

我看了你的代码,问题出在全局变量sPrepend上——递归的时候它会累积所有走过的组名,不会在处理完一个分支后回溯,导致后面的路径串味了。咱们把前缀改成递归函数的参数,让每个递归分支都用自己独立的前缀,就能解决这个问题。

下面是修正后的代码,我加了注释说明:

function buildList(groups, currentPrefix = '') {
  // 遍历当前层级的所有组
  for (const groupName in groups) {
    const group = groups[groupName];
    // 构建新的前缀:如果当前前缀为空,直接用当前组名;否则用" - "连接
    const newPrefix = currentPrefix ? `${currentPrefix} - ${groupName}` : groupName;
    
    if (group.names) {
      // 找到names数组,遍历输出每个名称的完整路径
      group.names.forEach(name => {
        console.log(`${newPrefix} - ${name}`);
      });
    } else {
      // 没有names,递归处理子组,传递新的前缀
      buildList(group, newPrefix);
    }
  }
}

// 你的示例JSON数据
const oGroups = { 
  "groupZ": { "names": [ "Steve", "Henry" ] }, 
  "groupY": { "groupA": { "names": [ "Laura" ] }, "groupB": { "names": [ "Alice", "Bob", "Neil" ] } }, 
  "groupX": { "groupC": { "groupD": { "names": [ "Steph" ] } }, "groupE": { "names": [ "Aaron", "Dave" ] } } 
};

// 调用函数
buildList(oGroups);

代码说明:

  • 去掉了全局的sPrepend,改用currentPrefix作为函数参数,每次递归都会生成新的前缀,不同分支的路径不会互相干扰。
  • 处理前缀拼接时,判断当前前缀是否为空,避免开头出现多余的" - "符号。
  • 当遇到包含names的组时,直接遍历数组输出完整路径;否则递归处理子组,把当前组名加入前缀后传递下去。

运行这段代码,就能得到你想要的输出:

groupZ - Steve
groupZ - Henry
groupY - groupA - Laura
groupY - groupB - Alice
groupY - groupB - Bob
groupY - groupB - Neil
groupX - groupC - groupD - Steph
groupX - groupE - Aaron
groupX - groupE - Dave

这样不管嵌套多少层,都能正确生成每个名称的完整组路径啦。

内容的提问来源于stack exchange,提问作者tripRev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:17:46