I've been working on parsing a csv file:
let lines = csvData.split(/\r\n|\n/);
let headers = lines[0].split(',');
for (let i = 1; i < lines.length; i++) {
let values = lines[i].split(',');
let item = {};
for (let j = 0; j < headers.length; j++) {
item[headers[j]] = values[j];
}
items.push(item);
}
return items;
Now, the issue I'm facing is that all the data extracted from the csv file are in string format. I want to convert them into JSON and remove their type so that I can assign them to variables with different types. However, since I don't know the specific type of each variable, I can't directly use parseInt or parseFloat.
Every time I try to parse the values into JSON, they end up being strings like "1234" instead of integers like 1234. Usually, passing JSON data without specifying types works fine, but after converting the csvData into JSON, everything becomes a string. I suspect this might have something to do with the split function converting it into a string?
In terms of a solution, I thought about passing the type as an argument to the function, like readCsvFile<T>(csvData)
, and then checking if I can do something like this:
if (typeof(T[headers[j]]) == 'number') {
item[headers[j]] = parseFloat(values[j]);
} else {
item[headers[j]] = values[j];
}
However, attempting T[header[j]] doesn't pass the compilation process.