I'm currently navigating through a nested JSON object and I'm facing challenges in accessing the sub items within it.
Below is a snippet of the JSON file I'm working with. It has successfully passed the JSONLint test, so it should be in proper format.
JSON
[{
"fleetcheckitemid": "1",
"checkitemdesc": "Engine oil level",
"answers": [{
"fleetcheckid": "1",
"checkvaluedesc": "Ok"
}, {
"fleetcheckid": "2",
"checkvaluedesc": "Low"
}, {
"fleetcheckid": "3",
"checkvaluedesc": "Top-Up Required"
}]
}, {
"fleetcheckitemid": "2",
"checkitemdesc": "Water level",
"answers": [{
"fleetcheckid": "1",
"checkvaluedesc": "Ok"
}, {
"fleetcheckid": "2",
"checkvaluedesc": "Low"
}, {
"fleetcheckid": "3",
"checkvaluedesc": "Top-Up Required"
}]
}, {
"fleetcheckitemid": "3",
"checkitemdesc": "Brake fluid level",
"answers": [{
"fleetcheckid": "1",
"checkvaluedesc": "Ok"
}, {
"fleetcheckid": "2",
"checkvaluedesc": "Low"
}, {
"fleetcheckid": "3",
"checkvaluedesc": "Top-Up Required"
}]
}]
I can successfully retrieve the "fleetcheckitemid" and "checkitemdesc", but I'm encountering difficulties with accessing the "answers" values.
In my controller, I have the following code. However, I am encountering an error as soon as I try to iterate through the inner .each() loop: "TypeError: Cannot read property 'length' of undefined"
app.js
$http.get("http://mymadeupdomain/api/getfleetchecks.php?fleetid=" + $scope.newFleetIDValue).success(function(data)
{
$scope.data = data;
console.log("$scope.data: " + $scope.data); // SUCCESS - [object Object], ... [object Object]
$scope.answersArray = [];
console.log("$scope.answers: " + $scope.answers); // EMPTY ARRAY - NOT INITIALIZED YET
// Unable to access sub-items (answers) here
$.each($scope.data, function(index, element)
{
var itemDescription = element.checkitemdesc;
console.log("itemDescription: " + itemDescription); // SUCCESS - Engine Oil Level
var fleetcheckitemid = element.fleetcheckitemid;
console.log("fleetcheckitemid: " + fleetcheckitemid); // SUCCESS - 1....34
$.each(this.answers, function(index, element)
{
var answers = element.answers;
var fleetcheckid = element.fleetcheckid;
console.log("element.fleetcheckid: " + element.fleetcheckid); // NOT WORKING
console.log("fleetcheckid: " + fleetcheckid); // NOT WORKING
});
});
});
What am I doing wrong in this code snippet? Could the [] brackets surrounding the answers in the JSON be the cause of this issue?