The AJAX call below returns a JSON file with several JSON entries just like this, one after the other. I pulled these from the console. Note, the entries do not arrive in an array.
{"display_name":"ESL_SC2","_id":30220059,"name":"esl_sc2","type":"user","bio":"For standings, schedule, and results, visit http://www.intelextrememasters.com/","created_at":"2012-05-02T09:59:20Z","updated_at":"2017-12-12T19:05:29Z","logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/esl_sc2-profile_image-d6db9488cec97125-300x300.jpeg","_links":{"self":"https://api.twitch.tv/kraken/users/esl_sc2"}}
{"display_name":"RobotCaleb","_id":54925078,"name":"robotcaleb","type":"user","bio":null,"created_at":"2014-01-13T04:07:33Z","updated_at":"2017-12-12T18:02:11Z","logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/robotcaleb-profile_image-9422645f2f0f093c-300x300.png","_links":{"self":"https://api.twitch.tv/kraken/users/robotcaleb"}}
I am not interested in every key/property in every file, rather I only want a few of the values injected into the DOM.
Here is the JQ I have in place. It's the updateUserInfo function that is at issue. It fires for every key in every JSON file, which is what I wish to avoid.
$(document).ready(function () {
var streamersArr = ["ESL_SC2", "OgamingSC2", "cretetion", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
$("#all-btn").on("click", function () {
streamersArr.forEach(function(user) {
getUserInfo(user);
console.log(user);
});
});
function getUserInfo (user) {
$.ajax({
crossDomain: true,
dataType: "jsonp",
url: "https://wind-bow.gomix.me/twitch-api/users/" + user,
data: {
"stream_type": "all"
},
// take contents of JSON file from API and update html
success: function (json) {
console.log(JSON.stringify(json));
updateUserInfo(json);
},
// display when AJAX request fails
error: function () {
alert("AJAX user info request has failed!");
}
});
}
function updateUserInfo (json) {
var htmlMediaClass;
var htmlMediaBody;
Object.keys(json).forEach(function(key) {
htmlMediaClass += '<div class="media">';
htmlMediaClass += '<div class="media-left media-top">';
if (key.match(/_links.self/gi)){
htmlMediaClass = '<a href="' + json[key] + '"' + '>';
}
if (key.match(/logo/gi)){
htmlMediaClass = '<img class="media-object" src="' + json[key] + '"' + 'alt="user logo">';
}
htmlMediaClass += '</a>';
htmlMediaClass += '</div>';
htmlMediaBody += '<div class="media-body">';
htmlMediaBody += '<div class="row">';
htmlMediaBody += '<div class="col-md-4">';
if (key.match(/display_name/gi)){
htmlMediaBody = json[key];
}
htmlMediaBody += '</div>';
htmlMediaBody += '<div class="col-md-8">';
if (key.match(/bio/gi)){
htmlMediaBody = json[key];
}
htmlMediaBody += '</div>';
htmlMediaBody += '</div>';
var finalHTML = htmlMediaClass + htmlMediaBody;
updateDOM(finalHTML);
});
}
function updateDOM (html) {
$("#data-row").append(html);
}
});