迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中将 CSV 加载到数组

作者:迹忆客 最近更新:2023/03/10 浏览次数:

CSV 是一个文本文件。它使用逗号作为分隔符来分隔不同的值。

在本文中,我们将使用 JavaScript 将 CSV 文件加载到数组中。

jQuery 库提供了 jquery-csv 插件,可以将 CSV 文件读入数组。

例如,

array = $.csv.toArrays(csv, {
  delimiter: "'", 
  separator: ';', // Sets a custom field separator character
});

我们可以使用 delimiterseparator 属性设置自定义分隔符和分隔符。最终结果存储在一个数组中。

我们将使用 FileReader 类将所需的 CSV 文件作为字符串读取。要将其存储到数组中,我们将使用 slice()split()map() 函数。slice() 函数有助于返回一个新数组,其中包含实现它的旧数组的一部分。map() 函数通过提供为数组中的每个元素提供的函数来帮助返回一个新数组。split() 函数使用指定的分隔符帮助将字符串拆分为数组形式的子字符串。

请参考下面的代码。

function csv_To_Array(str, delimiter = ",") {
      const header_cols = str.slice(0, str.indexOf("\n")).split(delimiter);
      const row_data = str.slice(str.indexOf("\n") + 1).split("\n");
      const arr = row_data.map(function (row) {
        const values = row.split(delimiter);
        const el = header_cols.reduce(function (object, header, index) {
          object[header] = values[index];
          return object;
        }, {});
        return el;
      });

      // return the array
      return arr;
    }

我们假设文件的第一行包含标题。slice() 函数从开头开始到第一个 \n 索引,并使用 split() 函数根据分隔符将字符串拆分为数组。同样,我们使用这两个函数来存储行。接下来,我们将行映射到数组。我们使用 map() 函数将行的每个值拆分为一个数组。reduce() 函数与标题一起使用以创建一个对象,将行的值与必要的标题一起添加,并返回此对象。这个对象被添加到数组中。最后,我们返回最终的数组,它是一个对象数组。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便