2

I would like the Html table to reflect the same column order as shown in the json. I am expecting this...

Company, 2007, 2008, 2009

This is the json response in data.d

[{"Company":"ABC Infotech","2007":"3","2008":"3","2009":"4"},{"Company":"TPS Software","2007":"6","2008":"8","2009":"6"},{"Company":"XYZ InfoSystem","2007":"1","2008":"3","2009":"6"}]

The function to create the Html table returns a column order as this...

2007, 2008, 2009, Company

The following script returns the json perfectly. I have tried various json to html table scripts and when converted via eval or JSON.parse they seem to be sorting the column names?

Is there a fix?

$(document).ready(function () {

    //the div in the page...
    //<div id="output"style="margin: 10px;"></div>

    $.makeTable = function (mydata) {
        var table = $('<table class="table table-striped table-bordered" >');
        var tblHeader = "<tr>";
        for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
        tblHeader += "</tr>";
        $(tblHeader).appendTo(table);
        $.each(mydata, function (index, value) {
             var TableRow = "<tr>";
             $.each(value, function (key, val) {
                 TableRow += "<td>" + val + "</td>";
             });
             TableRow += "</tr>";
             $(table).append(TableRow);
        });
        return ($(table));
    };

    return_pivot();
    function return_pivot() {
        //get file count
        var jsonText = JSON.stringify({
            new_file: "DataForPivot.xls",
            row_field: "Company",
            data_field: "CTC",
            column_fields: "Year"
        });

        $.ajax({
            type: "POST",
            url: "Pivot.aspx/pivot",
            data: jsonText,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                if (data.d != "0") {
                    console.log(data.d)
                    var mydata = eval(data.d);
                    var table = $.makeTable(mydata);
                    $(table).appendTo("#output");
                } 
            }
        }); //end ajax call
    }
});
2
  • You might consider just building the HTML server side... Commented Sep 21, 2016 at 19:56
  • Need a javascript solution. Commented Sep 21, 2016 at 20:00

2 Answers 2

2

An Object is an unordered collection of properties , so the order of each property like you see into your string is not assured:

{"Company":"ABC Infotech","2007":"3","2008":"3","2009":"4"}

To preserve such an order you may add a new parameter to your makeTable function containing an array (so, ordered by index) of keys whose order must be respected.

My snippet:

$.makeTable = function (mydata, orderToRespect) {
  var table = $('<table class="table table-striped table-bordered" >');
  var tblHeader = "<tr>";
  orderToRespect.forEach(function(ele, index) {
    tblHeader += "<th>" + ele + "</th>";
  });
  tblHeader += "</tr>";
  $(tblHeader).appendTo(table);
  $.each(mydata, function (index, value) {
    var TableRow = "<tr>";
    orderToRespect.forEach(function(ele, index) {
      TableRow += "<td>" + value[ele] + "</td>";
    });
    TableRow += "</tr>";
    $(table).append(TableRow);
  });
  return ($(table));
};


//
// your data
// 

var mydata = [{"Company": "ABC Infotech", "2007": "3", "2008": "3", "2009": "4"},
                {"Company": "TPS Software", "2007": "6", "2008": "8", "2009": "6"},
                {"Company": "XYZ InfoSystem", "2007": "1", "2008": "3", "2009": "6"}];

//
// call the makeTable function with a new parameter
// containing the order to respect
//
var table = $.makeTable(mydata, ['Company', '2007', '2008', '2009']);


$(table).appendTo("#output");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="output" style="margin: 10px;"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

The columns returned in the json response are random, based on the customers data, I won't know the expected order.
@Rob I understand your problem but I cannot ignore an object does not have an order. You may try to use the string, before converting it to an array of object. In this way you may try to extract the order with your own parser. This is the alternative I see.
Agreed, will get the columns on the server and append them to the response. Thanks for this solution!
1

Your issue is that an object keys is always ordered numberic then alphabetic.

Try ordering the keys like below:-

function sortAlphaThenNumberic(a, b) {
  if (!isNaN(a) && !isNaN(b))
    return a > b;
  if (isNaN(a) && isNaN(b))
    return a.toLowerCase() > b.toLowerCase();
  if (isNaN(a))
    return false;
  return true;
}

$.makeTable = function(mydata) {
  var table = $('<table class="table table-striped table-bordered" >');
  var tblHeader = "<tr>";

  var orderedKeys = Object.keys(mydata[0]).sort(sortAlphaThenNumberic);

  for (var k in orderedKeys) tblHeader += "<th>" + k + "</th>";
  tblHeader += "</tr>";
  $(tblHeader).appendTo(table);
  $.each(mydata, function(index, value) {
    var TableRow = "<tr>";
    $.each(orderedKeys, function(key, val) {
      TableRow += "<td>" + value[val] + "</td>";
    });
    TableRow += "</tr>";
    $(table).append(TableRow);
  });
  return ($(table));
};

2 Comments

I've made a jsfiddle for this solution.
Thanks! But the json response is random, so I can't assume it's in a specific order. Data in the response is changing all the time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.