James Xu
James Xu

Reputation: 45

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>

Upvotes: -1

Views: 53

Answers (2)

Qodeer
Qodeer

Reputation: 166

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>";
}

Upvotes: 2

SR810
SR810

Reputation: 228

Make childAll = "" inside the 1st for loop since you want to start with an empty list for each parent.

Upvotes: 2

Related Questions