Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  153] [ 1]  / answers: 1 / hits: 17336  / 6 Years ago, sat, september 8, 2018, 12:00:00

PROBLEM:

Downloaded CSV file is blank (unparse() method to conver array/JSON to CSV).



DETAIL:

Papaparse is working fine when parse CSV file to JavaScript array. But when I feed that array data or JSON data to unparse() method, its not working.



Angular JS method:



$scope.downloadCSV = function(){
var csv = Papa.unparse($scope.final_array);
console.log($scope.final_array);
console.log(csv);
var csvData = new Blob([csv], {type: 'text/csv;charset=utf-8;'});
var csvURL = null;
if (navigator.msSaveBlob) {
csvURL = navigator.msSaveBlob(csvData, 'download.csv');
} else {
csvURL = window.URL.createObjectURL(csvData);
}
var tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', 'download.csv');
tempLink.click();
}


$scope.final_array contains data as:



enter



On above code, console.log(csv); displays blank on the console.



In short: var csv = Papa.unparse($scope.final_array); is not working.



UPDATE

The posted array help me to generate following table and the button Save Generated CSV is not working and the code posted is for the this action button.
enter


More From » arrays

 Answers
132

You are trying to unparse an array of arrays which is just plain data without the column names.



To use the column names you might want to use the array of objects version. Rewrite your final_array as:



$scope.final_array = [
{ question1: A, question2: A, question3: mike },
{ question1: A B, question2: B, question3: dan },
];


Alternatively you can separate your column names and the data in a single object as follows:



$scope.final_object = {
fields: [ question1, question2, question3 ],
data: [
[ A, A, mike ],
[ A B, B, dan, ],
],
};


If you need to convert $scope.final_array maybe the following snippet will help you:



function convertFinal(arrOfArr) {
return arrOfArr.map(function(arr) {
var obj = {};
for(var key in arr) {
if(arr.hasOwnProperty(key)) {
obj[key] = arr[key];
}
}
return obj;
});
}

var csv = Papa.unparse(convertFinal($scope.final_array));

[#53538] Tuesday, September 4, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucillemariselal

Total Points: 108
Total Questions: 97
Total Answers: 119

Location: Thailand
Member since Thu, May 6, 2021
3 Years ago
;