40 lines
1.0 KiB
JavaScript
40 lines
1.0 KiB
JavaScript
|
// CSV to JS object
|
||
|
function csvToObject(csvData) {
|
||
|
const rows = csvData.split('\n');
|
||
|
const headers = rows[0].split(',');
|
||
|
const dataArray = [];
|
||
|
|
||
|
for (let i = 1; i < rows.length; i++) {
|
||
|
const values = rows[i].trim().split(','); // trim to remove linebreak
|
||
|
if (rows[i] != '') {
|
||
|
//don't treat empty lines
|
||
|
const obj = {};
|
||
|
for (let j = 0; j < headers.length; j++) {
|
||
|
obj[headers[j]] = values[j];
|
||
|
}
|
||
|
dataArray.push(obj);
|
||
|
}
|
||
|
}
|
||
|
return dataArray;
|
||
|
}
|
||
|
|
||
|
|
||
|
// JS object to CSV
|
||
|
function objectToCsv(objArray) {
|
||
|
const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
|
||
|
let csv = '';
|
||
|
// field names in first line
|
||
|
const fields = Object.keys(array[0]);
|
||
|
csv += fields.join(',') + '\r\n'; // \r\n for cross platform compatibility
|
||
|
// data rows
|
||
|
for (let i = 0; i < array.length; i++) {
|
||
|
let line = '';
|
||
|
for (let index in array[i]) {
|
||
|
if (line !== '') line += ',';
|
||
|
line += array[i][index];
|
||
|
}
|
||
|
csv += line + '\r\n';
|
||
|
}
|
||
|
return csv;
|
||
|
}
|