0

I am trying to download some data as a CSV but I am getting this on the file:

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

I am using file-saver

And this is how I am doing it:

  const downloadFile = () => {

    const formatCSVData = shipmentsCSV.shipments.map(data => ({
      Courier: data.courierName,
      Status: data.status.name,
    }));

    console.log('formatCSVData', JSON.stringify(formatCSVData, null, 2));

    const blob = new Blob([formatCSVData], {
      type: 'text/csv;charset=UTF-8',
    });

    saveAs(blob, 'CSV.txt');
  };

That second console.log logs this (26 items but I am going to simplified to 4):

[
  {
    "Courier Name": "Hand Delivery",
    "Status": "Received"
  },
  {
    "Courier Name": null,
    "Status": "Pending"
  },
  {
    "Courier Name": null,
    "Status": "Canceled"
  },
  {
    "Courier Name": "FedEx",
    "Status": "Canceled"
  }
  ...
]

So, how can I print the data correctly on the CSV file?

Reacting
  • 3,765
  • 4
  • 24
  • 56
  • 1
    CSV is a bunch of lines, where each line contains strings separated by commas. Nowhere are you inserting commas or newline characters. You'll basically want something like `data.map(obj => obj.join(",")).join("\n")`, provided that `data` is an array of arrays. – Chris G Jan 10 '19 at 18:11
  • Possible duplicate of [How to convert JSON to CSV format and store in a variable](https://stackoverflow.com/questions/8847766/how-to-convert-json-to-csv-format-and-store-in-a-variable) – Chris G Jan 10 '19 at 18:13

1 Answers1

0

Try this solution:

How to convert JSON to CSV format and store in a variable

function ConvertToCSV(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]) {
                    if (line != '') line += ','

                    line += array[i][index];
                }

                str += line + '\r\n';
            }

            return str;
        }

And your code will be:

const downloadFile = () => {

    const shipments = shipmentsCSV.shipments.map(data => ({
      Courier: data.courierName,
      Status: data.status.name,
    }));

    const formatCSVData = ConvertToCSV(shipments);
    console.log('formatCSVData', JSON.stringify(formatCSVData, null, 2));

    const blob = new Blob([formatCSVData], {
      type: 'text/csv;charset=UTF-8',
    });

    saveAs(blob, 'CSV.txt');
  };
Rakesh Makluri
  • 590
  • 3
  • 9