Skip to content

Instantly share code, notes, and snippets.

@svierk
Last active October 23, 2022 15:10
Show Gist options
  • Select an option

  • Save svierk/7e42e06972f36e8cd2d0e39fa28c5f2d to your computer and use it in GitHub Desktop.

Select an option

Save svierk/7e42e06972f36e8cd2d0e39fa28c5f2d to your computer and use it in GitHub Desktop.
Parsing Logic for simple CSV File Upload
parse(csv) {
// parse the csv file and treat each line as one item of an array
const lines = csv.split(/\r\n|\n/);
// parse the first line containing the csv column headers
const headers = lines[0].split(',');
// iterate through csv headers and transform them to column format supported by the datatable
this.columns = headers.map((header) => {
return { label: header, fieldName: header };
});
const data = [];
// iterate through csv file rows and transform them to format supported by the datatable
lines.forEach((line, i) => {
if (i === 0) return;
const obj = {};
const currentline = line.split(',');
for (let j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
data.push(obj);
});
// assign the converted csv data for the lightning datatable
this.data = data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment