Reputation: 21
im learning JSON and encounter a problem when looping JSON. This is my JSON response
{
"success": 1,
"category": [{
"id": "1",
"category": "Editorial",
"created_at": "2019-11-05 18:10:31",
"firstname": "abc",
"lastname": "xyz"
}, {
"id": "2",
"category": "Sports",
"created_at": "2019-11-05 19:25:50",
"firstname": "abc",
"lastname": "xyz"
}, {
"id": "3",
"category": "Health",
"created_at": "2019-11-05 19:27:23",
"firstname": "abc",
"lastname": "xyz"
}, {
"id": "4",
"category": "Food",
"created_at": "2019-11-05 19:39:17",
"firstname": "abc",
"lastname": "xyz"
}]}
and this is my loop
for(var i = 0; i <= jsonData.category.length; i++){
console.log(jsonData.category[i]['firstname']);}
it does print in console but it gives me this error
Cannot read property 'firstname' of undefined at Object.success
Upvotes: 1
Views: 19
Reputation: 4678
Use <
instead of <=
. Otherwise you reach an undefined index.
for(var i = 0; i < jsonData.category.length; i++){
console.log(jsonData.category[i]['firstname']);
}
Upvotes: 1