[英]Load csv into array of dictionary using JavaScript
My knowledge of JavaScript is limited, but I am wanting to load a CSV file into an array of dictionaries. 我对JavaScript的了解有限,但是我想将CSV文件加载到词典数组中。 I have attached an example of the style that I am after, however, this would have to be dynamically changed as some tables could be quite large?
我已经附上了我所追求的样式的示例,但是,由于某些表可能很大,因此必须动态更改它?
Example CSV: CSV示例:
Vehicle ID, Vehicle Name, Category, KM
0001, Yaris, commute, 12560
0002, z350, personal, 5600
0003, Porche, business, 21040
Example Array: 示例数组:
var vehicles = [
{
"Vehicle ID": "0001",
"Vehicle Name": "Yaris",
"Category": "commute",
"KM": "12560.00"
},
{
"Vehicle ID": "0002",
"Vehicle Name": "Z350",
"Category": "personal",
"KM": "5600.09"
},
{
"Vehicle ID": "0003",
"Vehicle Name": "Porche",
"Category": "business",
"KM": "21040.70"
}
];
Any help would be greatly appreciated. 任何帮助将不胜感激。
Cheers 干杯
Well if I got you, this is what you need 好吧,如果我得到你,这就是你所需要的
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="app-wrapper">
<div>
<label for="file">Search File </label>
<input type="file" id="file">
</div>
</div>
<script>
(function () {
var fileInput = document.querySelector('#file');
var reader = new FileReader ();
fileInput.addEventListener('change', readCSVFile);
reader.addEventListener('loadend', processData);
function readCSVFile (e) {
reader.readAsText(e.target.files[0]);
}
function processData() {
var allTextLines = reader.result.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var row = {};
for (var j=0; j< headers.length; j++) {
row[headers[j].trim()] = data[j].trim();
}
lines.push(row);
}
}
console.log(lines);
}
})();
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.