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

5.1k views Asked by At

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

2

There are 2 answers

0
sainaen On BEST ANSWER

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>

2
Christian Landgren On

You don't need any framework to convert from json to csv.

// fields in the order you want them
const fields = ['ID', 'OrderNumber', 'OrderStatus', 'StartTime', 'FinishTime', 'canOp', 'OpDesc', 'UOM'];
const mapper = (key, value) => value === null ? '' : value // how to handle null values
const csv = [
  fields.join(','), // header row
  ...json.map((row) => fields.map((fieldName) => JSON.stringify(row[fieldName], mapper))).join(',')
]
console.log(csv.join('\r\n'))

Outputs:

ID,OrderNumber,OrderStatus,StartTime,FinishTime,canOp,OpDesc,UOM
"100","1000101","Good","18:10","20:50","True","Good to go","K"
"100","1000101","Good","18:10","20:50","True","Good to go","K"