When processing data from ther response in json in a for loop,
JSON:
{
"languages": [
{
"id": 1,
"name": "English",
},
{
"id": 2,
"name": "Norwegian",
},
{
"id": 3,
"name": "Dutch",
},
{
"id": 50,
"name": "French",
},
{
"id": 76,
"name": "Inuktitut",
}
]
}
TEST:
var jsonData = JSON.parse(responseBody);
var lng_count = jsonData.languages.length;
for (i=0;i<=lng_count;i++){
console.log(jsonData.languages[i].id);
}
I faced a problem that the test fails with an error
ERROR:
TypeError: Cannot read properties of undefined (reading 'id').
but when i do it in “while” it works as expected
var jsonData = JSON.parse(responseBody);
var lng_count = jsonData.languages.length;
i = 0;
while (i < lng_count){
console.log(jsonData.languages[i].id);
}
i++;
Can anybody explain what is wrong with loop “for” ?