I have 2 javascript requests that give back results in an array of objects.
The first object looks like this:
[Object {user_id="6", meta_value="5", user_nicename="richbai90", more...},
Object {user_id="7", meta_value="1", user_nicename="testing123", more...}]
the 2nd looks like this
[Object { usr="6", score="1 / 1", quiz_id="1"},
Object { usr="7", score="1 / 1", quiz_id="1"},
Object { usr="7", score="1/5", quiz_id="3"}]
Array 2 is the details of array one
What I need is a way to relate these together in javascript so that I can put the information from object 2 in the document where it needs to correspond with the information from object one. The easiest way I could think to do this would be to combine the arrays where the user ids were the same but this appears to be more difficult then I first thought. Here was my initial approach:
$.post(AjaxRequest.ajaxurl, {
action: "get_data"
})
.done(function (json) {
console.log(json);
var data = json;
for (var i = 0; i < json.length; i++) {
if (AjaxRequest.user_ID == json[i].user_id && json[i].Quizes == "1") {
$("#result_list").append("you have taken " + json[i].Quizes + " quiz");
} else if (AjaxRequest.user_id == json[i].user_id && json[i].Quizes != "1") {
$("#result_list").append("you have taken " + json[i].Quizes + " quizzes");
} else {
$("#result_list").append(json[i].user_nicename + " has taken " + json[i].Quizes + " quizzes" + "<br>");
}
}
getDetails(json);
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ', ' + error;
console.log('1st Request Failed: ' + err);
});
function getDetails(data) {
$.post(AjaxRequest.ajaxurl, {
action: "get_details"
})
.done(function (details) {
console.log(data);
console.log(details);
for (var i = 0; i < data.length; i++) {
for (var i2 = 0; i2 < details.length; i++) {
while (details[i2].usr == data[i].user_id) {
console.log(details[i2]);
break;
}
}
}
$("#loading").fadeOut('fast', function () {
$("#result_list").fadeIn('fast');
});
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ', ' + error;
console.log('2nd Request Failed: ' + err);
});
}
In this code block is where the work is happening
for (var i = 0; i < data.length; i++) {
for (var i2 = 0; i2 < details.length; i++) {
while (details[i2].usr == data[i].user_id) {
console.log(details[i2]);
break;
}
}
}
The issue is that once the while loop breaks it doesn't seem to go to the next itteration of the for loop as I would have expected instead data[i] gets undefined. If I remove the break; then data[i] is always == details[i2] and thus crashes the browser.
Maybe I'm making it harder than it needs to be?