-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsvToArray.html
98 lines (89 loc) · 2.41 KB
/
csvToArray.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<!--// Skip to content-->
<!--// Pull requests-->
<!--// Issues-->
<!--// Marketplace-->
<!--// Explore-->
<!--// @andythierry-->
<!--// nsebhastian /-->
<!--// javascript-csv-array-example-->
<!--// Public-->
<!--//-->
<!--// Code-->
<!--// Issues 3-->
<!--// Pull requests-->
<!--// Actions-->
<!--// Projects-->
<!--// Wiki-->
<!--// Security-->
<!--//-->
<!--// Insights-->
<!--//-->
<!--// javascript-csv-array-example/index.html-->
<!--// @nsebhastian-->
<!--// nsebhastian init OK-->
<!--// Latest commit ea89fd8 on 17 Apr 2021-->
<!--// History-->
<!--// 1 contributor-->
<!--// 54 lines (46 sloc) 1.61 KB-->
<head> </head>
<body>
<form id="myForm">
<input type="file" id="csvFile" accept=".csv" />
<br />
<input type="submit" value="Submit" />
</form>
<script>
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);
document.write(JSON.stringify(data));
};
reader.readAsText(input);
});
</script>
</body>
<!--//-->
<!--// © 2022 GitHub, Inc.-->
<!--//-->
<!--// Terms-->
<!--// Privacy-->
<!--// Security-->
<!--// Status-->
<!--// Docs-->
<!--// Contact GitHub-->
<!--// Pricing-->
<!--// API-->
<!--// Training-->
<!--// Blog-->
<!--// About-->
<!--//-->
<!--// Loading complete-->