简体   繁体   中英

Creating table from json using javascpirt

First of all I'm pretty new to javascript. I tried to create a table from json file. I read up some information and follow some tutorials, and I finally was able to create a table that appeared on the web browser. But I found out that the different arrays are always sorted, and it allows only unique values. For example here is the json:

var json = {
            "data": [
                {
                    "number": "13",
                    "position": "GK",
                    "name": "John"
                },
                {
                    "number": "2",
                    "position": "CB",
                    "name": "Bill"
                },
                {
                    "number": "26",
                    "position": "CB",
                    "name": "Nick"
                }

And when I put the information in the table I'm creating it looks something like this:

| Number | Position | Name |
|   2    |    GK    | John |
|   13   |    CB    | Bill |
|   26   |undefined | Nick |

As you can see the numbers from json file does not match their names and the numbers are sorted, for example John is not number 2 but number 13 . The other thing is it doesnt allow same values - there are 2 CB positions, but it shows only 1 and the other is shown as undefined .

Here is what I wrote so far:

     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"
            }

I know I misunderstood something when learning about pushing objects into array, and I tried to change it in any way, but it still appeares the same. Thank you in advance for your time.

I think the problem that you are experiencing is that in javascript, hashes are not ordered, so when you do for(var k in object.number) , you can not expect each number to come out in the same order that you put it in.

Arrays, however will preserve order.

I don't think you need your object variable at all. I think you can just do this:

JSONDataLouder = {
  getPlayers: function(json) {

  var u = {
    "number": [],
    "position": [],
    "name": []
  };

  var personData; 
  for (var i = 0; i < json.data.length; i++) {
    personData = json.data[i];
    u.number.push(personData.number);
    u.position.push(personData.position);
    u.name.push(personData.name);
  }

  return u;
}

Different test data would like give you even crazier results. There are actually a lot of issues in the code, but I think the main thing getting you off track is mixing your data structures. Before you think about the table itself, think about your intermediate data structure, namely some sort of (in effect) two dimensional array.

The thing is though, that you don't need an intermediate structure. You already have an array in your JSON.data. In your code, you are converting this array into something else.

Consider the following, which omits some of what you are doing, but cuts to the core of the table generation.

var json = {
    "data": [
        {
            "number": "13",
            "position": "GK",
            "name": "John"
        },
        {
            "number": "2",
            "position": "CB",
            "name": "Bill"
        },
        {
            "number": "26",
            "position": "CB",
            "name": "Nick"
        }
    ]
};


function objToTable(obj) {
    var data = obj.data;
    var output = '<table>';
    for (var i = 0; i < data.length; i++) {
        output += '<tr>';
        output += '<td>' + data[i].number + '</td>';
        output += '<td>' + data[i].position + '</td>';
        output += '<td>' + data[i].name + '</td>';
        output += '</tr>\n'; // added newline for console readability
    }
    output += '</table>';
    return output;
}


console.log(objToTable(json));

Perhaps this could help you

  var json = { "data": [ { "number": "13", "position": "GK", "name": "John" }, { "number": "2", "position": "CB", "name": "Bill" }, { "number": "26", "position": "CB", "name": "Nick" }] }; console.log('| Número | Posición | Nombre |'); $.each(json.data, function(id, item) { console.log(item.number + '|' + item.position + '|' + item.name + '|'); }); 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM