web*_*Dev 5 javascript arrays papaparse
问题:
下载的CSV文件为空(unparse()将数组/ JSON转换为CSV的方法).
详细信息:
将CSV文件解析为JavaScript数组时,Papaparse工作正常.但是,当我将该数组数据或JSON数据提供给unparse()方法时,它无法正常工作.
Angular JS方法:
$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();
}
Run Code Online (Sandbox Code Playgroud)
$scope.final_array 包含以下数据:
在上面的代码中,console.log(csv);控制台上显示为空白.
简而言之:var csv = Papa.unparse($scope.final_array);不起作用.
您正在尝试解析一个数组数组,这些数组只是没有列名的纯数据.
要使用列名,您可能希望使用对象数组版本.重写你final_array的:
$scope.final_array = [
{ question1: "A", question2: "A", question3: "mike" },
{ question1: "A B", question2: "B", question3: "dan" },
];
Run Code Online (Sandbox Code Playgroud)
或者,您可以将列名和单个对象中的数据分开,如下所示:
$scope.final_object = {
fields: [ "question1", "question2", "question3" ],
data: [
[ "A", "A", "mike" ],
[ "A B", "B", "dan", ],
],
};
Run Code Online (Sandbox Code Playgroud)
如果您需要转换$scope.final_array,则以下代码段可以帮助您:
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));
Run Code Online (Sandbox Code Playgroud)
Your mistake: if we view your console screenshot we will see that you have some mishmash in your array code from arrays and objects. In your code you have some like this:
var array =
[
[question1: "A", question2: "A"],
[question1: "A B", question2: "B"]
];
Run Code Online (Sandbox Code Playgroud)
But it is incorrect and must to be some like this:
var array =
[
{question1: "A", question2: "A"},
{question1: "A B", question2: "B"}
];
Run Code Online (Sandbox Code Playgroud)
You have to correct it.
Working example
See this Codepen demo because StackOverflow snippets are in sandbox and because of this do not work.
var array =
[
[question1: "A", question2: "A"],
[question1: "A B", question2: "B"]
];
Run Code Online (Sandbox Code Playgroud)
var array =
[
{question1: "A", question2: "A"},
{question1: "A B", question2: "B"}
];
Run Code Online (Sandbox Code Playgroud)
For further information see the documentation from Papa's unparse function.