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

时间:2017-08-10 01:42:57

标签: javascript

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

非常感谢任何帮助。

干杯

1 个答案:

答案 0 :(得分:1)

如果我找到你,那就是你需要的

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

中查看