Reputation: 63
in the following code, i was trying to extract data from json, and there was few errors occur, which i dont understand. In my previous post, someone mentioned that it was related to closure issues. Can anyone please explain why this issues still occur eventhough i already change the "var" to "let" in both for loop?
I would like to try the bind solution, but, i dont understand the steps. this is because i am referring to for loop array in json file.
function displayData(data) {
var json = JSON.parse(data);
alert (json.projects[0].task_data[1].taskName); //working
for (let i = 0; i < json.projects.length; i++) {
$.ajax({ url: epridlist, method: 'GET' }).then(function (datas) {
alert (json.projects[i].projName); //success load the value
});
for (let j = 0; j < json.projects[i].task_data.length; j++) {
$.ajax({url: tasklist,method: 'GET'}).then(function (data)
{alert (json.projects[i].task_data[j].taskName);});//success only on first row, next row value is undefined
alert (json.projects[0].task_data[1].taskName); //undefined
}
}
}
this is the json data
{"projects":[{"projName":"1","task_data":[{"taskName":"1","task_detail_data":[{"h_sun":"0.00","h_mon":"0.00","h_tue":"0.00","h_wed":"0.00","h_thu":"0.00","h_fri":"0.00","h_sat":"0.00"}]},[{"taskName":"2","task_detail_data":[{"h_sun":"0.00","h_mon":"0.00","h_tue":"0.00","h_wed":"0.00","h_thu":"0.00","h_fri":"0.00","h_sat":"0.00"}]}]]},{"projName":"2","task_data":[{"taskName":"3","task_detail_data":[{"h_sun":"0.00","h_mon":"0.00","h_tue":"0.00","h_wed":"0.00","h_thu":"0.00","h_fri":"0.00","h_sat":"0.00"}]}]}]}
Thanks
Upvotes: 0
Views: 92
Reputation: 7753
It seems your JSON data has inconsitant structure.
When viewing JSON in Json Viewer program first element of task_data
is an object while the second is an array (see below picture):
Below line in your code will cause an issue:
json.projects[0].task_data[1].taskName
Upvotes: 2
Reputation: 2340
This problem occur here: json.projects[0].task_data[1].taskName
you're triying to accede an object how does not exists. task_data array in the second position is an array, not an object. The soluction to your problem is use json.projects[i].task_data[0].taskName
acceding to the object instead of the array.
Upvotes: 2