. Advertisement .
..3..
. Advertisement .
..4..
You can quickly convert CSV to array in JavaScript with additional libraries like Papa Parse in Node.js. But to get a better understanding of this language, you should master the way to do so in its vanilla form first.
Convert CSV To Array In JavaScript Without Frameworks Or Libraries
Example
Here is the body of an HTML file that can load a CSV file from your computer and convert its data to a JavaScript array:
<body>
<form class="content" id="uploadForm">
<input type="file" id="csvUploader" accept=".csv" />
<input type="submit" value="Convert" />
</form>
<script>
const uploadForm = document.getElementById("uploadForm");
const csvFile = document.getElementById("csvUploader");
function csv2array(csvdata, delimiter = ",") {
const header = csvdata.slice(0, csvdata.indexOf("\n")).split(delimiter);
const rows = csvdata.slice(csvdata.indexOf("\n") + 1).split("\n");
const arrdata = rows.map(function (row) {
const values = row.split(delimiter);
const el = header.reduce(function (object, header, index) {
object[header] = values[index];
return object;
}, {});
return el;
});
return arrdata;
}
uploadForm.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 = csv2array(text);
for (i = 0; i < data.length; i++)
document.writeln(JSON.stringify((data[i])) + "<br />");
console.log(data)
};
reader.readAsText(input);
});
</script>
</body>
It will print out result like this:
{"Username":"booker12"," Identifier":"9012","One-time password":"12se74","Recovery code":"rb9012","First name":"Rachel","Last name":"Booker","Department":"Sales","Location":"Manchester"}
{"Username":"grey07"," Identifier":"2070","One-time password":"04ap67","Recovery code":"lg2070","First name":"Laura","Last name":"Grey","Department":"Depot","Location":"London"}
{"Username":"johnson81"," Identifier":"4081","One-time password":"30no86","Recovery code":"cj4081","First name":"Craig","Last name":"Johnson","Department":"Depot","Location":"London"}
{"Username":"jenkins46"," Identifier":"9346","One-time password":"14ju73","Recovery code":"mj9346","First name":"Mary","Last name":"Jenkins","Department":"Engineering","Location":"Manchester"}
{"Username":"smith79"," Identifier":"5079","One-time password":"09ja61","Recovery code":"js5079","First name":"Jamie","Last name":"Smith","Department":"Engineering","Location":"Manchester"}
How exactly does this work?
To convert CSV to array in JavaScript, we create a form that contains two input tags: one for selecting the CSV file and one for confirming the upload.
- The JavaScript at the end listens to the submit event of the second input element. We don’t need to refresh the page, which is the default behavior of a submit event in JavaScript.
- The preventDefault() method of the Event interface can stop this and let us handle the data right away. We use a FileReader object to read the CSV file saved locally on our computer.
- Remember that when you select or drag and drop a file in a browser, it will be represented by a File object in JavaScript. The FileReader object helps us read the content of this File object asynchronously.
- After creating the FileReader object, we set up an onload function for it and call the readAsText() function to start the reading in the background. This instructs the FileReader object to read the uploaded file as text.
- The csv2array() function does the heavy lifting and converts this text content into a JavaScript array. It processes each row, splitting it by the delimiter and creating one array element after another.
- When an array is returned from the csv2array, we print it into the HTML document with document.writeln().
Conclusion
You can convert CSV to array in JavaScript using other libraries and frameworks as well. But using plain JavaScript will help you grasp the basics and improve your skills in this language.
Leave a comment