问题
Forewarning, I am new to js and I crafted the code below was taken from Retrieve parsed data from CSV in Javascript object (using Papa Parse)
my goal = parse a csv file into an array, and use that array in a few other operations. I can see that the file is getting parsed properly via the "console.log("Row:", row.data);", but I cannot figure out how to get that entire array/dataset into a separate variable, much less into the "doSAtuff" function.
function parseData(url, callBack) {
Papa.parse(url, {
download: true,
header: true,
dynamicTyping: true,
comments: "*=",
step: function(row) {
console.log("Row:", row.data);
},
complete: function(results) {
callBack(results.data);
}
});
}
function doStuff(data) {
//Data should be usable here, but is emtp
console.log("doStuff - console log '" + data + "' ?");
}
parseData(inputFile, doStuff);
I think I want to do something like...
var csvArray = [];
csvArray = Papa.parse(url, {
download: true,
header: true,
dynamicTyping: true,
comments: "*
...
<some other stuff with csvArray>
but i'm a bit wrapped around the axle at the moment.
回答1:
I know that if you remove the header: true
setting then Papa.parse will return you an Array instead of an Object.
Alternatively you could just convert the object that is returning into an array using something like:
function _arrayify(obj) { return Object.keys(obj).map(function (k) { return obj[k]; }) }
回答2:
const url = "https://www.papaparse.com/resources/files/normal.csv";
let results;
const csvData = Papa.parse(url, {
dynamicTyping: true,
download: true,
header: true,
comments: "*=",
complete: function(data) {
results = data.data
}
});
setTimeout(()=> {
console.log(results[0].ISSN)
}, 1500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.5.0/papaparse.min.js">
</script>
来源:https://stackoverflow.com/questions/51013182/how-to-get-papa-parse-results-into-an-array