JS functions: convert object to csv, convert csv to object

This commit is contained in:
Sam Hadow 2024-02-23 00:37:15 +01:00
parent 708b625fbe
commit 3e92c644fd

39
web/csv.js Normal file
View File

@ -0,0 +1,39 @@
// 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;
}