Last active
January 1, 2022 17:13
-
-
Save DemonDaddy22/4ea5c4b44a8390872396f7db276d2684 to your computer and use it in GitHub Desktop.
Util function to convert CSV into an array of objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const isEmptyString = <T>(value: string | T): boolean => | |
typeof value !== 'string' || !value?.trim()?.length; | |
const csvToArray = (csvString: string, delimiter: string = ','): Array<any> => { | |
if (isEmptyString(csvString)) return []; | |
/* | |
get the first piece of string by slicing the string till the first new line character is encountered | |
split the sliced string about the delimiter to get the list of headers | |
*/ | |
const headers = csvString.slice(0, csvString.indexOf('\n')).split(delimiter); | |
/* | |
get the rows of data by splitting the remaining string about the new line character | |
*/ | |
const dataRows = csvString.slice(csvString.indexOf('\n') + 1).split('\n'); | |
/* | |
split each row about the delimiter to get an array of values | |
iterate over the headers to create key-value pairs of each header along with the corresponding value | |
add these objects to the required array | |
*/ | |
const resultingArray = dataRows.map((row: string) => { | |
const rowValues: Array<string> = row.split(delimiter); | |
const headerValueMapping = headers.reduce(( | |
accumulatedMapping: {[key: string]: string}, currentHeader: string, index: number, | |
) => { | |
accumulatedMapping[currentHeader] = rowValues[index]; | |
return accumulatedMapping; | |
}, {}); | |
return headerValueMapping; | |
}); | |
return resultingArray; | |
}; | |
/* | |
Example | |
try { | |
const csvData = fs.readFileSync('./sample.csv', 'utf8'); // type of csvData is string | |
const resultingArray = csvToArray(csvData); | |
fs.writeFileSync('./sample.json', JSON.stringify({ data: resultingArray })); | |
} catch (err) { | |
console.log(err); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment