Search code examples
javascriptarraysobjectfor-in-loop

Accessing a nested object with loop but too many undefines?


I'm working with an object literal and trying to access the nested array and iterate through a loop but it keeps displaying 59 times and 5 times again as undefined in my console but then displays the arrays. How do I stop it from doing the undefined in the console? Thanks!

Screenshot of console log

var votingData = {
  candidates: [{
  name: "Harry S. Truman",
  party: "Democratic"
},
{
  name: "Thomas E. Dewey",
  party: "Republican"
},
{
  name: "Strom Thurmond",
  party: "Dixiecrat"
}]

}

for(var candidate in votingData) {
  if(votingData.hasOwnProperty(candidate)) {
    for (let i = 0, j = votingData[candidate].length; i < j; i++) {
    console.log(votingData[candidate][i].name, votingData[candidate]
    [i].party);
   }
 }
}

Solution

  • Your for/in loop is contributing to the problem as it is not needed because votingData contains only one property, candidates. Since there's just one property, you can access it directly, no need for a loop.

    You only need to loop through the arrays which are in the votingData.candidates property and for that, you can either use a standard counting for loop, which you are doing or, even better, use the Array.forEach() mechanism for looping. It's better because it gives you direct access to the array element being looped over, without the need for an indexer and that allows the syntax to be much clearer, which in turn, tends to avoid bugs like this.

    var votingData = {
      candidates: [{
      name: "Harry S. Truman",
      party: "Democratic"
    },
    {
      name: "Thomas E. Dewey",
      party: "Republican"
    },
    {
      name: "Strom Thurmond",
      party: "Dixiecrat"
    }],
    };
    
    // Just loop through the arrays in the votingData.candidates property
    votingData.candidates.forEach(function(candidate) {
      // Now "candidate" is an object, so standard "dot notation" to access
      // any/all properties of the current object is the way to go.
      console.log(candidate.name, candidate.party);
    });