Created
May 22, 2019 13:54
-
-
Save jupegarnica/2b65953c533be5be040d501a0653b28b to your computer and use it in GitHub Desktop.
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 csvToJson = (data, delimiter = ',') => { | |
const titles = data.slice(0, data.indexOf('\n')).split(delimiter); | |
return data | |
.slice(data.indexOf('\n') + 1) | |
.split('\n') | |
.map(v => { | |
const values = v.split(delimiter); | |
return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {}); | |
}); | |
}; | |
CSVToJSON('col1,col2\na,b\nc,d'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}]; | |
CSVToJSON('col1;col2\na;b\nc;d', ';'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment