0

I want to export data in CSV format and these showed up in the file. Please see the screenshot below. This must be dynamic.

https://i.stack.imgur.com/wVd1K.jpg

enter image description here

This is my code:

function questionCSV(filename, data){
  var csv = [];
  var innerCounter = 0;
  for (var i = 0; i < data.length; i++){

    var row_data = [];
    let conv_obj = Object.keys(data[i][innerCounter]).length;
    for (var j = 0; j < conv_obj ; j++) {
      if(j == 0){
        row_data.push(i+1);
      }else{
        row_data.push(data[i][j]);
        innerCounter++;
      }
    }
    innerCounter *= 0;
    csv.push(row_data.join(","));
  }
  downloadCSV(csv.join("\n"), filename);
}
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
  • Possible duplicate of [How can I parse a CSV string with Javascript, which contains comma in data?](https://stackoverflow.com/questions/8493195/how-can-i-parse-a-csv-string-with-javascript-which-contains-comma-in-data) – Jacob Thomas May 09 '19 at 00:25
  • If you're not apposed to using npm, [this csv module](https://www.npmjs.com/package/csv) would probably take care of your issue. – Lawrence May 09 '19 at 00:25
  • I'm not sure why you're pushing the same data three times, but apparently `data[i][j]` is an object. Since you `join` the array, it calls the `toString()` method of the object, which results in "[object Object]". – Heretic Monkey May 09 '19 at 00:28
  • Datas are not the same, its the length of the data. –  May 09 '19 at 00:29
  • Possible duplicate of [what does \[object Object\] mean?](https://stackoverflow.com/questions/4750225/what-does-object-object-mean) – Heretic Monkey May 09 '19 at 00:31

1 Answers1

0

You can JSON.stringify variable data[i][j]

row_data.push(JSON.stringify(data[i][j])); 

and update CSV content by structure of data[i][j]

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62