Created
April 29, 2022 21:47
-
-
Save n8jadams/d917facf3302acfc69c4b825c31edb42 to your computer and use it in GitHub Desktop.
Convert a CSV string to 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
function csvStringToArrOfObjs(csvString) { | |
const rowsWithColumNames = csvString.split('\n') | |
const columnNames = rowsWithColumNames[0].split(',').map(columnName => columnName.replace('\r', '')) | |
const rows = rowsWithColumNames.slice(1) | |
return rows.map(row => { | |
const obj = {} | |
const parts = row.split(',').map(columnName => columnName.replace('\r', '')) | |
columnNames.forEach((columnName, index) => { | |
obj[columnName] = parts[index] | |
}) | |
return obj | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment