JavaScript 如何将2D数组转换为逗号分隔值(CSV)字符串

JavaScript 如何将2D数组转换为逗号分隔值(CSV)字符串

给定一个2D数组,我们需要使用JS将其转换为逗号分隔值(CSV)字符串。

Input:
[ [ "a" , "b"] , [ "c" ,"d" ] ]
Output:
"a,b 
 c,d"
Input:
[ [ "1", "2"]
["3", "4"]
["5", "6"] ]
Output:
"1,2
3,4
5,6"

为了实现这一目标,我们必须了解一些在这方面有帮助的数组原型函数:

Join函数: Array.prototype.join( )函数用于用一个字符/字符串连接数组中的所有字符串。

示例:

[ "a","b"].join( ",") will result in : "a,b"

Map函数: Array.prototype.map()返回一个新数组,其中包含我们提供的函数对每个元素的调用结果。

示例:

arr= ["a","b"]

// Adding "c" to each element
newArray = arr.map( item => item + "c") 
value of newArray = ["ac", "bc"]

方法: 我们将使用map函数和join函数将每个1D行组合成一个字符串,使用逗号分隔。然后使用join函数将所有单独的字符串组合起来,使用“\n”作为分隔符。

示例: 在这个示例中,我们将使用map()和join()函数将CSV值转换为字符串。

<script>
    // Create CSV file data in an array  
    var array2D = [ 
                    [ "a" , "2"] ,
                    [ "c" ,"d" ] 
                  ];
     
    // Use map function to traverse on each row
    var csv = array2D
      .map((item) => {
       
        // Here item refers to a row in that 2D array
        var row = item;
         
        // Now join the elements of row with "," using join function
        return row.join(",");
      }) // At this point we have an array of strings
      .join("\n");
       
      // Join the array of strings with "\n"
    console.log(csv);
</script>

输出:

a,2
c,d

解释: 我们首先在二维数组上使用了map函数来遍历每一行,然后使用join函数来使用逗号连接该行中的元素数组。接下来,map函数返回一个字符串数组,我们使用”\n”来连接这些字符串数组。因此最终得到CSV字符串。

另一种方法: 我们甚至可以使用for循环来遍历数组,而不是使用map函数。

示例: 在这个示例中,我们将使用JavaScript循环来将CSV转换为字符串。

<script>
    var csv="";
    //create CSV file data in an array  
    var array2D = [ 
                    [ "a" , "2"] ,
                    [ "c" ,"d" ] 
                  ];
     
    for (var index1 in array2D) {
      var row = array2D[index1];
       
      // Row is the row of array at index "index1"
      var string = "";
       
      // Empty string which will be added later
      for (var index in row) {
        // Traversing each element in the row
        var w = row[index];
         
        // Adding the element at index "index" to the string
        string += w;
        if (index != row.length - 1) {
          string += ",";
          // If the element is not the last element , then add a comma
        }
      }
      string += "\n";
       
      // Adding next line at the end
      csv += string;
      // adding the string to the final string "csv"
    }
    console.log(csv);
</script>

输出:

a,2
c,d

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程