Warm tip: This article is reproduced from stackoverflow.com, please click
arrays dictionary javascript csv

Converting dataset into proper CSV notation for downloading using JavaScript

发布于 2020-03-27 10:24:10

I currently have the following dataset:

this.set1 // == [111000, 111000, 110000, 110000, 109000]
this.set2 // == [2.073921204, 2.156188965, 2.210624695, 2.210624695, 2.286842346]
this.set3 // == [527.6497192, 522.3652954, 529.675415, 529.675415, 533.8148804]
this.set4 // == [530.6442261, 524.7432861, 532.2295532, 532.2295532, 536.545166]
this.set5 // == [80.73879242, 80.92513275, 80.95175934, 80.95175934, 80.79203796]

I tried the following code to convert this data to my needed CSV data:

// Reference to pulled-data arrays
let data = [
  this.set1
  this.set2
  this.set3
  this.set4
  this.set5
];

// Convert data arrays to CSV format
const CSVURL = 'data:text/csv;charset=UTF-8,';
let formattedData = data.map(e => e.join(',')).join('\n');
let encodedData = CSVURL + encodeURIComponent(formattedData);

// Generic download CSV function
downloadFile('name.csv', encodedData);

However, this outputted a CSV file of the following format:

desc 1

How would I convert the data to this format for use in CSV?:

desc 2

Edit: The similarities to the other post were only partial. See comments for full solution.

Questioner
About7Deaths
Viewed
66
About7Deaths 2019-07-04 00:03

Utilizing partial advice given by @Heretic Monkey (for transposing the data) and @codeWonderland (for adding category names), I have arrived at the following solution:

// Reference to pulled-data arrays
let data = [
  this.set1
  this.set2
  this.set3
  this.set4
  this.set5
];

// NEW
// Reference to data array names in same order as aforementioned data array
const dataNames = [
  'set1',
  'set2',
  'set3',
  'set4',
  'set5',
]

// NEW
// Add label to each column
data.forEach((datum, index) => {
  datum.unshift(dataNames[index]);
});

// Convert data arrays to CSV format
const CSVURL = 'data:text/csv;charset=UTF-8,';
let transposedData = data[0].map((col, i) => data.map(row => row[i])); // NEW: TRANSPOSE DATA
let formattedData = transposedData.map(e => e.join(',')).join('\n'); // Modified
let encodedData = CSVURL + encodeURIComponent(formattedData);

// Generic download CSV function
downloadFile('name.csv', encodedData);

Also noting the recent addition for alternative column labeling by @Kosh Very , quoted as:

// pull arrays by headers
data[0].forEach(h => data.push(this[h]));