I'd like to combine a set of $.each statements looping through an array of arrays containing objects of k:v
pairs into a single $.each
which I can increment.
Structure of array returned from PHP: an array of arrays containing objects.
PHP: this is what is run then sent back to the JavaScript.
array_push($allDataArray, $completedLevelData, $completedQuestData, $completedNPCData);
JavaScript:
I was originally using a separate $.each to loop through each array of objects as such. But I would like to consolidate these $.each statements into something smaller:
function updateData (functionToRun, callback) {
$.getJSON("phpscripts.php", {
"_player" : Player,
"_playerID" : UserID,
"_functionToRun" : functionToRun
},
function(result) {
var questIDs = [];
$.each(result[0], function (i, allData) {
$(".completedLevels").append("<br/>"+allData['levelname']);
});
$.each(result[1], function (i, allData) {
questIDs.push(allData['quest_id']);
$(".completedQuests").append("<br/>"+allData['quest_id']+ ", " + allData['questname']);
});
$.each(result[2], function (i, allData) {
$(".completedNPCs").append("<br/>"+allData['npc_name']);
});
etc...
To do this, I was just going to loop through with a for
and append... but the for
, unlike each, keeps looping and adding elements even when they're null. For example,
for (obj in result) {
for (obj2 in result[obj]) {
console.log(result[obj][obj2]['levelname']);
}
}
Gives:
mymap2
mymap
(9) undefined
[]
So it continues looping even if there is no data. I don't want it to do that.
That being said, I then tried a $.each
, and tried incrementing the parent array when it has looped through all the child arrays. Essentially mimicking above, but combining all $.each
into one $.each
, like so:
var k = 0, j = 0;
$.each(result[k], function (i, allData) {
//if you loop through all objects within parent object, move to next parent object
if (j == result[k].length) {
k++;
j=0;
}
j++;
etc...
But it just stops once it has looped through all of result[0]
, without incrementing k
. Any idea how to do this?
Edit: I tried the answer below, but it still shows undefined
s as being loaded:
for (var i = 0; i < result.length; i++) {
$.each(result[i], function (j, allData) {
$(".completedLevels").append("<br/>"+allData['levelname']);
});
}
The following is appended:
Completed levels:
- mymap
- undefined
- undefined
- undefined