Created
September 15, 2022 07:54
-
-
Save devbyray/da56ca238c5bca524a8a059f6260aef6 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 form = document.querySelector("#csvForm"); | |
const csvFileInput = document.querySelector("#csvInput"); | |
const textArea = document.querySelector("#csvResult"); | |
form.addEventListener("submit", function (e) { | |
e.preventDefault(); | |
const file = csvFileInput.files[0]; | |
const reader = new FileReader(); | |
reader.onload = function (e) { | |
const csvArray = csvToArr(e.target.result, ","); | |
textArea.value = JSON.stringify(csvArray, null, 4); | |
}; | |
reader.readAsText(file); | |
}); | |
function csvToArr(stringVal, splitter) { | |
const [keys, ...rest] = stringVal | |
.trim() | |
.split("\n") | |
.map((item) => item.split(splitter)); | |
const formedArr = rest.map((item) => { | |
const object = {}; | |
keys.forEach((key, index) => (object[key] = item.at(index))); | |
return object; | |
}); | |
return formedArr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment