Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rearrange CSV / JSON keys columns? (Javascript)

I am converting a JSON object array to CSV using Papa Parse JavaScript Library. Is there a way to have the CSV columns arranged in a certain way.

For e.g; I get the column as:

OrderStatus, canOp, OpDesc, ID, OrderNumber, FinishTime, UOM, StartTime

but would like to be arranged as:

ID, OrderNumber, OrderStatus, StartTime, FinishTime, canOp, OpDesc, UOM

The reason why I get the CSV as unarranged is because the JSON data looks like this:

json = [
{
    OrderStatus: "Good",
    canOp:"True",
    OpDesc:"Good to go",
    ID:"100",
    OrderNumber:"1000101",
    FinishTime:"20:50",
    UOM:"K",
    StartTime:"18:10"
},
...
]

Thanks

like image 968
Shahzad Ali Avatar asked Jun 23 '15 03:06

Shahzad Ali


1 Answers

Papa Parse allows to specify order of fields in the unparse() function:

var csv = Papa.unparse({
  fields: ["ID", "OrderNumber", "OrderStatus", "StartTime", "FinishTime", "canOp", "OpDesc", "UOM"],
  data: [{
      OrderStatus: "Good",
      canOp: "True",
      OpDesc: "Good to go",
      ID: "100",
      OrderNumber: "1000101",
      FinishTime: "20:50",
      UOM: "K",
      StartTime: "18:10"
    },
    // ...
  ]
});

console.log(csv);
<script src="https://unpkg.com/[email protected]/papaparse.min.js"></script>
<h3>See your dev console for the results</h3>
like image 124
sainaen Avatar answered Nov 13 '22 17:11

sainaen