Reputation: 68
I have been trying to access and display this data on a table in HTML
for a few hours now and have gotten nowhere. I have used the $.each
function but i believe I am somehow calling the data wrong please correct me if i am wrong The JSON data is laid out like this:
[
{
"id": "8ef2d135-73a3-4a58-8858-733f3882290a",
"userid": "8ef2d135-73a3-4a58-8858-733f3882290a",
"name": "MN-Carven",
"placement": 1,
"platform": "PC",
"value": 66.29059172668
},
{
"id": "b5af3e4f-8c43-48e4-8d04-e8adf0ae9808",
"userid": "b5af3e4f-8c43-48e4-8d04-e8adf0ae9808",
"name": "Tchanos.MTLK",
"placement": 2,
"platform": "PC",
"value": 65.32935808926
},
{
"id": "ee2fcc61-a8d9-4b57-8837-297ace438e3e",
"userid": "ee2fcc61-a8d9-4b57-8837-297ace438e3e",
"name": "Lion__.",
"placement": 3,
"platform": "PC",
"value": 57.44590079297
}
]
It is my understanding that i can access an array by using a $.each
function in javascript. I will post my javascript below. I am wanting to display multiple categories I.E: id, name, value etc..
$(function() {
var aliases = [];
$.getJSON('leaderboard.json', function(data) {
$.each(data.aliases, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.name + "</td>" + "<td>" + f.placement + "</td>" + "</tr>"
$(tblRow).appendTo("#leaderboard tbody");
});
});
});
Here is the HTML
for the table:
<table id="leaderboard">
<thead>
<tr>
<th>Username</th>
<th>Place</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="2">
</td>
</tr>
</tfoot>
</table>
I was so sure that I had been correct in using $.each
, but i believe i need some further guidance, any links to docs relating to my problems are welcome, thank you.
Upvotes: -1
Views: 71
Reputation: 68
SOLVED
The problem was my JQuery
Here is how this is solved:
$.getJSON('leaderboard.json', (data) => {
const tableData = data.reduce((pre, curr) => {
return pre + `<tr><td>${curr.name}</td><td>${curr.placement}</td></tr>`;
}, '');
$(tableData).appendTo('#leaderboard tbody');
});
Upvotes: 0
Reputation: 21
Part of the problem is that you're trying to iterate over data.aliases
, but aliases is not a part of the data object. Also, take a look at the reduce function for building your table body string. I think what you're looking for here could be accomplished with:
$.getJSON('leaderboard.json', (data) => {
const tableData = data.reduce((pre, curr) => {
return pre + `<tr><td>${curr.name}</td><td>${curr.placement}</td></tr>`;
}, '');
$(tableData).appendTo('#leaderboard tbody');
});
Upvotes: 1