Search code examples
javascriptarraysobjectrecursiontraversal

Climb and append nested objects/array


I am trying to understand how to recursively append a branching structure to an object.

I am trying to append children to an empty JSON object that when built out should look like the following.

nodeStructure: {
    text: { name: "Parent node" },
    children: [
        {
            text: { name: "First child" },
            children: [
                {
                  text: {name: "Grandchild"}
                }
            ]
        },
        {
            text: { name: "Second child" }
        }
    ]
}

Here is the most succinct version of that code.

trackFraud = async (fraudID) => {

  var root = chart_config.nodeStructure = newNode(fraudID);

  await fraudClimb(root, 1);

  var my_chart = new Treant(chart_config);

  function newNode(node) { return {text:{name:"fraud " + node}}; }

  async function fraudClimb(root, fraudID) {    
    var frauds = await findFraudByFromID.call(this, fraudID); // returns an array of "integers"

    if (frauds.length == 0) return;

    var children = root.children = [];
    for (var i = 0; i < frauds.length; i++) {
      children.push(newNode(frauds[i]));
      fraudClimb(children[i], frauds[i]);
    }   
  }
}

Now I am trying to wrap my head around how to traverse, or in this case append to, a structure that alternates every other level between arrays and objects

I guess the real question is how to pass an object around recursively and append to that original object.


Solution

  • I see two issues in your code:

    1. The first call to fraudClimb ignores the fraudID parameter that is available. Instead of:

      await fraudClimb(root, 1);
      

      I think you need:

      await fraudClimb(root, fraudID);
      
    2. The recursive call to fraudClimb is not awaited, yet you need the asynchronous operation to complete before you go on. So change this:

      fraudClimb(children[i], frauds[i]);
      

      to:

      await fraudClimb(children[i], frauds[i]);