提问人:hungryWolf 提问时间:2/14/2023 最后编辑:hungryWolf 更新时间:2/14/2023 访问量:79
为什么我的递归函数中的 for 循环不迭代两次?
Why doesn't the for loop in my recursive function iterate twice?
问:
我正在尝试运行以下代码。从我观察到的输出来看,它从不运行第二个循环,但在“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": []
}
]
}
]
}```
答: 暂无答案
评论
npm i alasql
input