Wednesday, November 11, 2015

jQuery array to CSV string - Two methods

The code below can be used to convert an name value type array in JavaScript to a CSV string, which could then be copied to the clipboard or returned as  .CSV file.

The first is for a JS array object with multiple arrays inside:

 function convertToCSV(objArray) {  
   var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;  
   var str = '';  
   for (var i = 0; i < array.length; i++) {  
     var line = '';  
     for (var index in array[i]) {  
       if (line !== '') line += ',';  
       line += array[i][index];  
     }  
     str += line + '\r\n';  
   }  
   return str;  
 }  
 function functionOne() {  
   var arrReturn = [];  
   var arrKeys = [];  
   var arrValues = [];  
   $.each(rowData, function (idx2, val2) {  
     var strKey = idx2;  
     var strValue = val2;  
     arrKeys.push(strKey);  
     arrValues.push(strValue);  
   });  
   arrReturn.push(arrKeys);  
   arrReturn.push(arrValues);  
   var result = convertToCSV(arrReturn);    
 }  

The second, simpler and faster version only supports one name value type array. e.g. var arr = ["Name":"Value];

 function functionTwo() {  
   var arrKeys = [];  
   var arrValues = [];  
   $.each(rowData, function (idx2, val2) {  
     var strKey = idx2;  
     var strValue = val2;  
     arrKeys.push(strKey);  
     arrValues.push(strValue);  
   });  
   var strKeys = arrKeys.join(",") + '\r\n';  
   var strValues = arrValues.join(",");  
   var result = strKeys.concat(strValues);   
 }  

JSFiddle - example with performance comparison to another method.

No comments: