I have a function that reads multiple json files. Now I want to modify it so that it can read csv files as well. I have another function that converts text into json arrays.
I am trying to do this, but I am getting an error Property 'csvtoarray' does not exist on type 'FileReader'.ts(2339)
readFile(reader: FileReader, file: File) {
const deferredResult = new Promise(resolve => {
reader.addEventListener('load', function getResult() {
console.log(file)
if(file["type"] == "application/json"){
resolve(reader.result as string)}
else if(file["type"]=="text/csv"){
resolve(this.csvtoarray(reader.result))
}
reader.removeEventListener('load', getResult)
})
})
How can I call my function that converts text into json arrays in this readFile
function?
My function that converts text into json arrays is:
csvtoarray(str,delimiter=','){
const headers = str.slice(0,str.indexOf("\n")).split(delimiter)
const rows = str.slice(str.indexOf("\n") + 1).split("\n")
const arr = rows.map(function(row) {
const values = row.split(delimiter);
const el = headers.reduce(function(object,header,index){
object[header] = values[index];
return object
},{});
return el
});
return arr
}