danielgoba84 danielgoba84 - 1 year ago 33
Javascript Question

Error while trying to iterate JSON array in JavaScript

I have JSON file, which i load in js code without problems using

JSON.parse()
(A reduced example of the file shown here, it's 25 items long):

{
"List": [
{ "Term": "Tos" },
{ "Term": "Gripa" },
{ "Term": "Catarro"},
{ "Term": "Flemas"}
]
}


When I iterate it accessing one item per iteration I have no problems, but when i try to increase the index to access to items per iteration it throws the following error (Comment in code shows the line with the problem):


console.log(searchTerms[j].Term);

TypeError: Cannot read property 'Term' of undefined


var data = fs.readFileSync(searchTermsFile);
var searchTerms = JSON.parse(data);
searchTerms = searchTerms.List;
for(var j=0;j<searchTerms.length;j+=4)
{
console.log(searchTerms[j].Term);
j+=1;
console.log(searchTerms[j].Term); /****<---- THIS LINE THROWS THE ERROR ****/
}

Answer Source

Your object contains 4 Term and your for loop count to 4 but j+=1 in last iteration make j=5 and there is no object in searchTerms[5].This is why your code doesn't work. I write sample program.I hope this helps you:

var data = {
    "List": [
        {"Term": "1"},
        {"Term": "2"},
        {"Term": "3"},
        {"Term": "4"},
        {"Term": "5"},
        {"Term": "6"},
        {"Term": "7"},
        {"Term": "8"},
        {"Term": "9"},
        {"Term": "10"},
        {"Term": "11"},
        {"Term": "12"}
    ]
};

function test() {
  var searchTerms = data.List;
  var j = 0;
  var currentFiveObject = [];
  for (j = 0; j < searchTerms.length; j += 5) {
    currentFiveObject = [];
    for (var i = 0; i < 5; i++) {
      if (j + i < searchTerms.length)
        currentFiveObject.push(searchTerms[j + i])
      else
        break;
    }
    console.log(currentFiveObject);
  }
}
test();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download