Skip to content

Instantly share code, notes, and snippets.

@jupegarnica
Created May 22, 2019 13:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jupegarnica/2b65953c533be5be040d501a0653b28b to your computer and use it in GitHub Desktop.
Save jupegarnica/2b65953c533be5be040d501a0653b28b to your computer and use it in GitHub Desktop.
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