Monisha
Monisha

Reputation: 31

Avoid sorting the json response data alphabetically on ajax call

I am creating a utility that reads the data present in the table and on clicking the download button the data from the table should get exported to a csv file.

Currently, the order of data getting from the server side is as expected. However, in the console on the client side, the data gets sorted in alphabetical order automatically. And hence the data downloaded in csv is also not in the expected order.

For eg. I have below data in table which I am reading in the given order itself:

Table Employee

Sr.No EmployeeID Name
1 12345 Abc

On clicking the download button, I see below order in the browser's console

{
  EmployeeID:12345,
  Name:Abc,
  Sr.No:1
}

And hence data in csv file downloaded looks as below

EmployeeID,Name,Sr.No
12345,Abc,1

I don't want this sorted order instead it should be as below

Sr.No,EmployeeId,Name
1,12345,Abc

function json2csv(objArray){

    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';
    for (var index in array[i]) {
         

        line += array[i][index] + ',';
    }
        line = line.slice(0,-1)
    str += line + '\r\n';
}

return str;
}

Upvotes: 0

Views: 534

Answers (1)

epascarello
epascarello

Reputation: 207511

I would store the order of the CSV columns you want, I would loop over that to generate the CSV data from the object and not rely on object key order.

var data = [{
  EmployeeID: 12345,
  Name: "ABC",
  "Sr.No": 1
}, {
  EmployeeID: 6789,
  Name: "CDE",
  "Sr.No": 2
}];

var csvOrder = ['Sr.No', 'EmployeeID', 'Name'];

function processCSV(columns, data) {
  var header = csvOrder.join(",");
  var rows = data.map(function (row) {
    const rowData = csvOrder.map(function (key){ return row[key]; });
    return rowData.join(",");
  });

  rows.unshift(header);
  return rows.join("\n\r");
}

console.log(processCSV(csvOrder, data));

Upvotes: 1

Related Questions