Starting off, I am relatively new to working with JavaScript. Recently, I attempted to generate a table using data from a JSON file. After researching and following some tutorials, I successfully displayed the table on a web browser. However, I noticed that the arrays in the JSON file were always sorted and only allowed unique values. Here is an example of the JSON data:
var json = {
"data": [
{
"number": "13",
"position": "GK",
"name": "John"
},
{
"number": "2",
"position": "CB",
"name": "Bill"
},
{
"number": "26",
"position": "CB",
"name": "Nick"
}
When I input this data into my table, it appears like this:
| Number | Position | Name |
| 2 | GK | John |
| 13 | CB | Bill |
| 26 |undefined | Nick |
As you can see, the numbers in the JSON file do not correspond correctly with the names, and they are sorted incorrectly. For instance, John
should have number 13
, not 2
. Additionally, it does not allow duplicate values - there are 2 entries for CB
position, but only one is displayed while the other shows as undefined
.
I have included the code snippet below:
JSONDataLouder = {
getPlayers: function(json) {
var object = {
"number": {}
, "position": {}
, "name": {}
};
var personData = null;
for (var i = 0; i < json.data.length; i++) {
personData = json.data[i];
object.number[personData.number] = 1;
object.position[personData.position] = 1;
object.name[personData.name] = 1;
}
var u = {
"number": []
, "position": []
, "name": []
};
for(var k in object.number) u.number.push(k);
for(var k in object.position) u.position.push(k);
for(var k in object.name) u.name.push(k);
return u;
}
,getTable: function(json) {
var obj = this.getPlayers(json);
var number = obj.number;
var position = obj.position;
var name = obj.name;
var table = this.createTable();
var headerRow = table.insertRow();
headerRow.insertCell().innerHTML = "Number";
headerRow.insertCell().innerHTML = "Position";
headerRow.insertCell().innerHTML = "Name"
for (var i = 0; i < number.length; i++) {
var secondRow = table.insertRow();
secondRow.style.textAlign="center";
secondRow.insertCell().innerHTML = number[i];
secondRow.insertCell().innerHTML = position[i];
secondRow.insertCell().innerHTML = name[i];
}
return table;
}
,render: function(mainDiv) {
$( mainDiv ).empty();
var json = {
"data": [
{
"number": "13",
"position": "GK",
"name": "John"
},
{
"number": "2",
"position": "CB",
"name": "Bill"
},
{
"number": "26",
"position": "CB",
"name": "Nick"
}
It seems I may have erred in understanding how to push objects into an array, despite attempting multiple fixes. Any assistance or insight would be greatly appreciated. Thank you for taking the time to help.