Reputation: 93
below is the json data. What I want to do Is, I want to check if the data is empty then, the No Records text will be shown. Below is my code. However I always get the Uncaught TypeError: Cannot read property 'detailedInfo' of undefined at line .detailedInfo[0]!=null
How can I fix that?
{
"status": "0",
"message": "",
"objectList": [{
"customerID": "A112",
"dateReg": "31/08/2015",
"detailedInfo": [{
"purchDate": "01/08/2015",
"prodCode": null,
"price": null,
"catefory": "BF"
}],
"subTotal": 23.00
}],
"objectList2": null
}
if(data.objectList[0].detailedInfo[0]!=null){
for(var i=0;i<data.objectList[0].detailedInfo.length;i++){
var purchaseDt = data.objectList[0].detailedInfo[i].purchDate;
var productCd = data.objectList[0].detailedInfo[i].prodCode;
var category = data.objectList[0].detailedInfo[i].myrEquiv;
$('#Date').append(purchaseDt);
$('#Code').append(productCd);
$('#Category').append(category);
}
}
else{
$('#noDataMsg').text("There is no record found");
$('#noDataMsg').show();
}
Upvotes: 2
Views: 412
Reputation: 14688
The reason you are getting the error is because data.objectList
is an empty array []
, so trying to access anything in offset zero, like data.objectList[0]
is undefined
, and hence you cannot access detailedInfo
of undefined
.
Why don't you simply test that the objectList exist and that it has a length greater than zero, like this;
if(data.objectList && data.objectList.length > 0){
...
} else {
...
}
The above should do it, unless you need to handle corner cases such as objectList suddenly being a string instead of an Array -- depending on your requirements, you may add a test to the if-statement of the typeof != 'string'
to handle that case as well.
Upvotes: 3
Reputation: 710
Check your data because data.objectList[0] does not have a detailedInfo property set.
Upvotes: 1