patternjavascriptMinor
Displaying data from JSON in a table
Viewed 0 times
displayingjsonfromdatatable
Problem
What do you think of my code? I know it is a little rough around the edges but as of two days ago I had no idea how to use jQuery or JavaScript.
$(document).ready(function () {
var json = {
"205100": {
"success": true,
"data": {
"type": "game",
"name": "MasterKin",
"steam_appid": 9000,
"required_age": 40,
"is_free": false,
"controller_support": "full",
"dlc": [212894, 212893, 208575, 208570]
}
}
};
var game_name = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
game_name.push({
ItemName: item.data.name //Changing the .name to .dlc or .type will then display that result
});
}
}
console.log(game_name);
var tr;
for (var i = 0; i ');
tr.append("" + game_name[i].ItemName + "");
$('table').append(tr);
}
});
Name
Solution
I don't know what the possible rest of your code looks like, so my opinion might be wrong. What I don't understand is why a lot of people use jQuery for the slightest bits nowadays. The display of the array could be done like this:
Update:
If you insist on using jQuery, cache the selector in a variable and re-use the variable. Overusing selectors can result in poor performance and since you're using the selector inside a loop this can easily occur.
Furthermore, give useful names to variables. Names like
var table = document.getElementById("displayTable"); //give this ID to your table
for (var i = 0; i < game_name.length; i++) {
var row = table.insertRow(i);
var cell = row.insertCell(0);
cell.innerHTML = game_name[i].ItemName;
}Update:
If you insist on using jQuery, cache the selector in a variable and re-use the variable. Overusing selectors can result in poor performance and since you're using the selector inside a loop this can easily occur.
var table = $('#displayTable');
for (var i = 0; i " + game_name[i].ItemName + "");
}Furthermore, give useful names to variables. Names like
tr or game_name are not meaningful, try tableRow and gameNames instead. I updated the JSFiddle working example.Code Snippets
var table = document.getElementById("displayTable"); //give this ID to your table
for (var i = 0; i < game_name.length; i++) {
var row = table.insertRow(i);
var cell = row.insertCell(0);
cell.innerHTML = game_name[i].ItemName;
}var table = $('#displayTable');
for (var i = 0; i < game_name.length; i++) {
table.append("<tr><td>" + game_name[i].ItemName + "</td></tr>");
}Context
StackExchange Code Review Q#70705, answer score: 3
Revisions (0)
No revisions yet.