I have a CSV file that looks like this:
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
...
I want to convert this data into an array of objects like this:
[
{ heading1: "value1_1", heading2: "value2_1", heading3: "value3_1", heading4: "value4_1", heading5: "value5_1" },
{ heading1: "value1_2", heading2: "value2_2", heading3: "value3_2", heading4: "value4_2", heading5: "value5_2" },
...
]
I’ve tried the following approach using JavaScript to read CSV data, but it hasn’t worked as expected:
<script type="text/javascript">
var allText =[];
var allTextLines = [];
var Lines = [];
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "file://d:/data.txt", true);
txtFile.onreadystatechange = function()
{
allText = txtFile.responseText;
allTextLines = allText.split(/\r\n|\n/);
};
document.write(allTextLines);
document.write(allText);
document.write(txtFile);
</script>
What’s the best approach to properly read and process the CSV data into the desired array format using JavaScript?