JavaScript .CSV到数组 [英] JavaScript .CSV to Arrays

查看:59
本文介绍了JavaScript .CSV到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.CSV文件.它具有4列和数千行.我想有4个数组,每列一个.我最近开始学习JavaScript.有人可以告诉我该怎么做吗?在Python中,这非常容易-只需几行代码.但是,看到JS中的相关文章后,我感到非常困惑.任何帮助,我们将不胜感激!

I have a .CSV file. It has 4 columns and thousands of rows. I want to have 4 arrays, one for each column. I recently started learning JavaScript. Can someone please tell me how to do this? In Python, this is extremely easy -- just a couple lines of code. However, I got super confused after seeing related posts in JS. Any help is greatly appreciated!

(PS:请让我知道是否需要导入"任何东西.任何参考文献也将非常有帮助!)

(PS: Please let me know if I need to "import" anything. Any references will be very helpful too!)

推荐答案

CSV可能很棘手,因为单元格可以转义逗号-

CSV can be tricky because cells can have escaped commas - comma-separated-values looks like a good choice since it is RFC 4180 compliant:

要安装软件包:

npm install comma-separated-values --save

然后在您的应用程序中使用它:

And then to use it your app:

import CSV from 'comma-separated-values';

const csv = new CSV(data, {header: true}).parse();

这将导致数组(行)的数组-将其转换为数组(列)的数组:

That will result in an array of arrays (of rows) - to transform that into an array of arrays (of columns):

const cols = [[],[],[],[]];
csv.forEach(row => {
  row.forEach((cell, idx) => {
    cols[idx].push(cell);
  });
})

这篇关于JavaScript .CSV到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆