Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve parsed data from CSV in Javascript object (using Papa Parse)

I'm sort of embarrassed to ask this question because it seems like it should be so obvious, but I'm pretty weak on dealing with async problems, and I'm confused on how to proceed.

I'm using Papa Parse (http://papaparse.com/docs.html#remote-files) to parse a remote CSV. I want to stash the result of the parse in an object to use later. Here's 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, results in an empty object being logged to the console. Any attempts at using dataset don't work because, of course, the dataset object hasn't actually received its data by the time the code executes. Can someone please help me refactor or explain how I deal with this?

like image 926
TheNovice Avatar asked Oct 08 '14 21:10

TheNovice


People also ask

How do I parse a csv file in JavaScript?

To convert or parse CSV data into an array , you need to use JavaScript's FileReader class, which contains a method called readAsText() that will read a CSV file data and parse the result as a string text. The FileReader class is a web API, so this solution only works in the browser.

What is Papa parse?

Papa Parse is the fastest in-browser CSV (or delimited text) parser for JavaScript. It is reliable and correct according to RFC 4180, and it comes with these features: Easy to use. Parse CSV files directly (local or over the network) Fast mode (is really fast)

How do you use Papaparse?

To get started with Papa Parse, first import the library. import Papa from 'papaparse'; When using the parse function, you can either choose to parse a string of delimited text, a local file, or a remote file URL. For this example, we will be parsing a local file that we received from React Dropzone in part one.


1 Answers

Is there a reason the dataset variable needs to be used outside of the function? The easiest way to ensure that the dataset is populated is to manipulate the dataset in the 'complete' function right after it is, well, populated.

An alternative is to add a callback like so:

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);
like image 131
colonelsanders Avatar answered Sep 27 '22 21:09

colonelsanders