Getting parsed data from a CSV in a Javascript object (using Para Parse)

I am embarrassed to ask this question because it seems like it should be so obvious, but I'm pretty weak at dealing with asynchronous issues, and I'm confused about how to proceed.

I am using Papa Parse ( http://papaparse.com/docs.html#remote-files ) to analyze remote CSV. I want to write the result of parsing into an object that will be used later. Here is my code:

var dataset = {}; Papa.parse("http://path/to/some.csv", { download: true, dynamicTyping: true, complete: function(results) { dataset = results.data; } }); console.log(dataset); 

This, of course, leads to an empty object that registers to the console. Any attempts to use the data set do not work, because, of course, the data set object did not actually receive its data at the time the code was executed. Can someone please help me reorganize or explain how I deal with this?

+6
source share
1 answer

Is there a reason why a dataset variable should be used outside of a function? The easiest way to ensure that the data set is populated is to manipulate the data set in a β€œfull” function immediately after it is filled.

An alternative is to add a callback as follows:

 function doStuff(data) { //Data is usable here console.log(data); } function parseData(url, callBack) { Papa.parse(url, { download: true, dynamicTyping: true, complete: function(results) { callBack(results.data); } }); } parseData("tests/sample.csv", doStuff); 
+19
source

Source: https://habr.com/ru/post/976454/


All Articles