使用Javascript:转换CSV到单独的数组的键和值 [英] Javascript: convert CSV to separate arrays for keys and values

查看:134
本文介绍了使用Javascript:转换CSV到单独的数组的键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将CSV数据JavaScript数组已经在这里讨论,但这是另一种情况。

Converting CSV data to Javascript arrays was already discussed here, but this is another case.

假设我们的CSV格式化结构类似这样的数据:

Assuming we have CSV-formated data structured like this:

one,two
three,four
five,six

我们可以使用拆分()函数或类似的 jQuery的-CSV 爸爸解析把它转换成一个JS数组结构类似

We can use split() function or libraries like jquery-csv or Papa Parse to convert it into a JS array structured like:

[['one', 'two'], ['three', 'four'], ['five', 'six']]

但如何将其转化成分别包含第一和第二'列'的数据数组?这样的:

But how to convert it into arrays containing data of first and second 'column' respectively? Like:

[['one', 'three', 'five'], ['two', 'four', 'six']]

我们可以,当然,遍历获得的键值对数组和推键和值到不同的数组,但有一种方式来获得它的结构像这样直接从CSV?

We can, of course, iterate through obtained key-value pair arrays and push keys and values into separate arrays, but is there a way to get it structured like this directly from CSV?

解析CSV数据到一个数组可以是资源足够饿了,所以这是好事,跳过不必要的行动。

Parsing CSV data into an array can be resource hungry enough, so it is good to skip unnecessary actions.

推荐答案

您可以使用以下功能来转阵列:

You can use below function to transpose your array:

transpose = function(a) {

  // Calculate the width and height of the Array
  var w = a.length ? a.length : 0,
    h = a[0] instanceof Array ? a[0].length : 0;

  // In case it is a zero matrix, no transpose routine needed.
  if(h === 0 || w === 0) { return []; }

  /**
   * @var {Number} i Counter
   * @var {Number} j Counter
   * @var {Array} t Transposed data is stored in this array.
   */
  var i, j, t = [];

  // Loop through every item in the outer array (height)
  for(i=0; i<h; i++) {

    // Insert a new row (array)
    t[i] = [];

    // Loop through every item per item in outer array (width)
    for(j=0; j<w; j++) {

      // Save transposed data.
      t[i][j] = a[j][i];
    }
  }

  return t;
};
transpose([['one', 'two'], ['three', 'four'], ['five', 'six']]);

的jsfiddle

来源: HTTP:// WWW。 shamasis.net/2010/02/transpose-an-array-in-javascript-and-jquery

这篇关于使用Javascript:转换CSV到单独的数组的键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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