Skip to content

Instantly share code, notes, and snippets.

@djibe
Created May 8, 2024 13:35
Show Gist options
  • Save djibe/8d14191076cedb9612fe6f52ad3f4198 to your computer and use it in GitHub Desktop.
Save djibe/8d14191076cedb9612fe6f52ad3f4198 to your computer and use it in GitHub Desktop.
VSC to JSON
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'}];
// https://github.com/Chalarangelo/30-seconds-of-code/blob/master/content/snippets/js/s/csv-to-json.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment