Search code examples
javascriptjsoncsvpapaparse

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


Solution

  • 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>