I'm trying to run the below code. From the output I've observed, it never runs a second loop, but there's supposed to be a second loop at 'propa'. Code on JS fiddle: 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)));
The current output looks something like this, but there is a second child expected at the 'propa' property level. But instead it just branches out in 1 direction and doesn't go to the other branch via for loop.
{
"data": {
"Main_head": "My main head",
"prop1": "val1",
"prop2": "val2"
},
"children": [
{
"data": {
"propa": "2"
},
"children": [
{
"data": {
"prop3": "12",
"prop6": "ABC"
},
"children": []
}
]
}
]
}```