Search code examples
javascriptfor-loopnested-loops

why Java Script nested loop gone wrong?


I have nested arrays which i want to list the children who belong to their parenets.

But the result obviously has gone wrong, it lists all the children in the array even they don't belong to the parents.

Just can't work out what's gone wrong.

var family = [ 
 { name:"parentOne",
   children:[ "John", "jack"]
},
 { name:"parentTw0",
   children: [ "jane", "joe"]
},
 { name:"parentThree",
   children: [ "Terry", "Noah"]
},
]

all = "";
childAll = "";
for (i = 0; i < family.length; i++) {

    for (j = 0; j < family[i].children.length; j++) {
        childAll += family[i].children[j] +"<br>" ;
    }

  all += family[i].name + "<br>" + " " + childAll + "<br>";
}
document.getElementById("demo").innerHTML = all;
<p id="demo"></p>


Solution

  • It does not reset the childAll.

    all = "";
    childAll = "";
    for (i = 0; i < family.length; i++) {
        // After one loop the childAll contains all the previous ones
        for (j = 0; j < family[i].children.length; j++) {
            childAll += family[i].children[j] +"<br>" ;
        }
    
      all += family[i].name + "<br>" + " " + childAll + "<br>";
    }
    

    Should be

    all = "";
    for (i = 0; i < family.length; i++) {
        // Reset every loop
        childAll = "";
    
        for (j = 0; j < family[i].children.length; j++) {
            childAll += family[i].children[j] +"<br>" ;
        }
    
      all += family[i].name + "<br>" + " " + childAll + "<br>";
    }