为什么我的递归函数中的 for 循环不迭代两次?

Why doesn't the for loop in my recursive function iterate twice?

提问人:hungryWolf 提问时间:2/14/2023 最后编辑:hungryWolf 更新时间:2/14/2023 访问量:79

问:

我正在尝试运行以下代码。从我观察到的输出来看,它从不运行第二个循环,但在“propa”处应该有第二个循环。JS 小提琴上的代码:https://jsfiddle.net/g0z87pvk/

const alasql = require('alasql');

function convertToTree1(arr, keysReadOnly, myObj={data:{},children:[]}, vals=[], keyIdx=0) {
    if (keyIdx === keysReadOnly.length) {
        console.log('returning early!')
        return myObj;
    }

    console.log('--------------------', String(keyIdx + 1))
    console.log(myObj, vals, keyIdx)
    const cols = keysReadOnly.slice(0, keyIdx+1);
    const colsStr = cols.join(', ');
    const currKey = keysReadOnly[keyIdx];

    let whereConditions = '';

    if (vals.length) {
        whereConditions = cols
            .slice(0, keyIdx)
            .map((col, idx) => `${col} = '${vals[idx]}'`)
            .join(' and ');
    }
     
    whereConditions = whereConditions.length > 1 ? `where ${whereConditions}` : '';
    const query = `
        select ${colsStr}
        from ? as t
        ${whereConditions}
        group by ${colsStr}`;
    console.log('\n', query, '\n');

    res = alasql(query, [arr]);
    console.log('res', res)

    if (res.length == 1) {
        myObj.data = {
            ...myObj.data,
            [currKey]: res[0][currKey],
        };

        vals = cols
            .map((col) => res[0][col])
            .filter((val) => val.length);

        myObj = convertToTree1(arr, keysReadOnly, myObj, vals, keyIdx+1);
    } else {
        for (let i = 0; i < res.length; ++i) {
            console.log('xxxxxxxxxxxxxxxx', i, res.length)

            let myObj1 = {
                data: {[currKey]: res[i][currKey]},
                children: [],
            };

            vals = cols
                .map((col) => res[i][col])
                .filter((val) => val.length);

            console.log('!!!!!!!!!!!!!!! calling convert to tree1 with: ', myObj1, vals, keyIdx+1)
            myObj1 = convertToTree1(arr, keysReadOnly, myObj1, vals, keyIdx+1);
            myObj.children = [...myObj.children, myObj1];
        }
    }

    return myObj;
}

// trying to call the code like this

const input = [
    {
        "Main_head": "My main head",
        "prop1": "val1",
        "prop2": "val2",
        "propa": '2',
        "prop3": '12',
        "prop6": "ABC",
    },
    {
        "Main_head": "My main head",
        "prop1": "val1",
        "prop2": "val2",
        "propa": '2',
        "prop3": '12',
        "prop6": "ABC",
    },
    {
        "Main_head": "My main head",
        "prop1": "val1",
        "prop2": "val2",
        "propa": '3',
        "prop3": '12',  
        "prop6": "BCD",
    },
    {
        "Main_head": "My main head",
        "prop1": "val1",
        "prop2": "val2",
        "propa": '2',
        "prop3": '12',  
        "prop6": "ABC",
    },
];

cols = Object.keys(input[0]);
console.log(JSON.stringify(convertToTree1(input, cols)));

当前输出如下所示,但在“propa”属性级别有第二个子项。但相反,它只是在一个方向上分支,而不是通过 for 循环转到另一个分支。

{
  "data": {
    "Main_head": "My main head",
    "prop1": "val1",
    "prop2": "val2"
  },
  "children": [
    {
      "data": {
        "propa": "2"
      },
      "children": [
        {
          "data": {
            "prop3": "12",
            "prop6": "ABC"
          },
          "children": []
        }
      ]
    }
  ]
}```

JavaScript 节点 .js 算法 递归 alasql

评论

1赞 WOUNDEDStevenJones 2/14/2023
请编辑您的问题,使其成为一个最小的可重复示例。按原样,尚不清楚您的预期输出是什么,并且问题中的代码包括能够运行它的其他库,因此其他人不容易测试它。如果你能缩小可能破坏的范围(例如,删除所有查询逻辑),并可能为代码的某些部分添加一些注释,你就更有可能从其他人那里得到有用的响应。
0赞 hungryWolf 2/14/2023
@WOUNDEDStevenJones但是,如果我们删除 alasql 代码,任何查看代码的人都需要编写过滤器,然后自行按代码分组。 会让它变得更简单,不是吗?npm i alasql
0赞 WOUNDEDStevenJones 2/14/2023
当然,但这是要求任何看到这个问题的人切换到他们的本地开发环境,安装一个 npm 包等,只是为了首先运行它。这可能没问题,但你为人们测试你当前代码设置的门槛越低,你就越有可能得到一个快速/可靠的答案。把它变成一个 jsfiddle 更容易:)jsfiddle.net/ehbk9zc8
0赞 hungryWolf 2/14/2023
是的,我的坏,修复了,现在代码可以工作了。工作 jsfiddle: jsfiddle.net/g0z87pvk .谢谢你的建议,jsfiddle 和讽刺的微笑:D。input
0赞 Mulan 2/15/2023
输出应该是什么样子的?

答: 暂无答案