From 3e92c644fd7e5c78d0d3b6410fe09589c1cf637d Mon Sep 17 00:00:00 2001 From: Sam Hadow Date: Fri, 23 Feb 2024 00:37:15 +0100 Subject: [PATCH] JS functions: convert object to csv, convert csv to object --- web/csv.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 web/csv.js diff --git a/web/csv.js b/web/csv.js new file mode 100644 index 0000000..232f573 --- /dev/null +++ b/web/csv.js @@ -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; +}