gpt4 book ai didi

javascript - 使用 JavaScript 将 csv 加载到字典数组中

转载 作者:行者123 更新时间:2023-11-30 21:16:47 26 4
gpt4 key购买 nike

我对 JavaScript 的了解有限,但我想将 CSV 文件加载到字典数组中。我附上了一个我所追求的样式的示例,但是,这必须动态更改,因为某些表可能非常大?

示例 CSV:

Vehicle ID, Vehicle Name, Category, KM
0001, Yaris, commute, 12560
0002, z350, personal, 5600
0003, Porche, business, 21040

示例数组:

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"
}
];

如有任何帮助,我们将不胜感激。

干杯

最佳答案

好吧,如果我找到你,这就是你需要的

<!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>

你可以在这个link中查看

关于javascript - 使用 JavaScript 将 csv 加载到字典数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45603122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com