首页 > 解决方案 > 如何将 .CSV 文件解析为数组,以便在代码中进一步操作?

问题描述

我有兴趣从本地拥有的 .csv 文件中获取数据,将其作为字符串读取,然后将该字符串转换为数组。网上有很多关于类似过程的资料,但大多数指南都假定要操作的文件将作为程序的输入提供,而在我的情况下,我已经有数据并且需要它作为数组以便我可以使用它用于其他事情。我已经尝试操纵各种解决方案,以便他们做到这一点,但我无法完全弄清楚 - 下面的一个看起来很有希望(并且做了我想要做的)但我无法弄清楚如何将本地文件作为 FileReader 的输入:

<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

任何帮助将不胜感激 - 如果这不是很清楚,我很抱歉,我对此很陌生。理想情况下,我希望此代码将“MOCK_DATA.csv”之类的内容作为输入,而不是外部提供的输入。

标签: javascripthtmlarrayscsv

解决方案


推荐阅读