Skip to content

Instantly share code, notes, and snippets.

@firedynasty
Created February 25, 2023 20:52
Show Gist options
  • Save firedynasty/d02fb6498de23188e535dec147ba1081 to your computer and use it in GitHub Desktop.
Save firedynasty/d02fb6498de23188e535dec147ba1081 to your computer and use it in GitHub Desktop.
CSV Loader MOC
<body>
<form id="myForm">
<input type="file" id="csvFile" accept=".csv" />
<br />
<input type="submit" value="Charger" />
</form>
</body>
//https://github.com/nsebhastian/javascript-csv-array-example/blob/master/index.html
const myForm = document.getElementById("myForm");
const csvFile = document.getElementById("csvFile");
function csvToArray(str, delimiter = ",") {
// slice from start of text to the first \n index
// use split to create an array from string by delimiter
const headers = str.slice(0, str.indexOf("\n")).split(delimiter);
// slice from \n index + 1 to the end of the text
// use split to create an array of each csv value row
const rows = str.slice(str.indexOf("\n") + 1).split("\n");
// Map the rows
// split values from each row into an array
// use headers.reduce to create an object
// object properties derived from headers:values
// the object passed as an element of the array
const arr = rows.map(function (row) {
const values = row.split(delimiter);
const el = headers.reduce(function (object, header, index) {
object[header] = values[index];
return object;
}, {});
return el;
});
// return the array
return arr;
}
myForm.addEventListener("submit", function (e) {
e.preventDefault();
const input = csvFile.files[0];
const reader = new FileReader();
reader.onload = function (e) {
const text = e.target.result;
const data = csvToArray(text);
console.log(data);
document.write(JSON.stringify(data));
};
reader.readAsText(input);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment