0

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": []
        }
      ]
    }
  ]
}```

hungryWolf
  • 391
  • 1
  • 3
  • 15
  • 1
    Please edit your question to be a [minimal reproducible example](https://stackoverflow.com/help/how-to-ask). As is, it's not clear what your expected output is, and the code in the question includes additional libraries to be able to run it, so it's not easily testable by others. If you could narrow down the scope of where this might be breaking (e.g. remove all of the query logic) and maybe add some comments for what certain parts of the code are expected to do, you're much more likely to get a useful response from others. – WOUNDEDStevenJones Feb 14 '23 at 15:12
  • @WOUNDEDStevenJones but if we remove alasql code any one reviewing the code needs to write filter and then group by code on their own. `npm i alasql` would make make it much simpler, isn't it? – hungryWolf Feb 14 '23 at 15:16
  • Sure, but that's asking anybody looking at this question to switch to their local development environment, install an npm package, etc. just to run this in the first place. That might be fine, but the lower you set the bar for people to be able to test your current code, the more likely you are to get a quick/solid answer. Making this into a jsfiddle is even easier :) https://jsfiddle.net/ehbk9zc8/ – WOUNDEDStevenJones Feb 14 '23 at 15:19
  • yeah, my bad, fixed the `input`, now the code works. Working jsfiddle: https://jsfiddle.net/g0z87pvk/ . Thanks for the suggestion, jsfiddle and sarcastic smile :D . – hungryWolf Feb 14 '23 at 15:22
  • what is the output *supposed* to look like? – Mulan Feb 14 '23 at 17:44

0 Answers0