Hello,
Im having a problem with a given task.
The task is to write a JavaScript code that would transfer data from a txt file looking like this:
14
151
1223
12415
13
into a CSV file with “0” added before the number so all have total of 8 digits. I was planing to do it with padStart() method but besides that im pretty much clueless
How am I supposed to import local txt file into JS while doing operations on the txt and save it as csv?
Eddit:
as for now my code looks something like this:
//-------grab a file -------
const input = document.querySelector(‘input[type=“file”]’)
input.addEventListener(‘change’, function (e) {
return input.files},false)
//--------save as CSV--------
function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;
data = args.data || null;
if (data == null || !data.length) {
return null;
}
columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';
keys = Object.keys(data[0]);
result = '';
result += keys.join(columnDelimiter);
result += lineDelimiter;
data.forEach(function(item) {
ctr = 0;
keys.forEach(function(key) {
if (ctr > 0) result += columnDelimiter;
result += item[key];
ctr++;
});
result += lineDelimiter;
});
return result;
}
function downloadCSV(args) {
var data, filename, link;
var csv = convertArrayOfObjectsToCSV({
data: input
});
if (csv == null) return;
filename = args.filename || 'export.csv';
if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
link.click();
}
However the first part of the code where is const input doesnt seem to work as intendeed. The 2nd part which is supposed to save given txt worked well when the data (data: input) was given with a var like var input = [“1”,“2”,“3”].