检索CSV在Javascript对象解析的数据(使用帕帕解析) [英] Retrieve parsed data from CSV in Javascript object (using Papa Parse)

查看:265
本文介绍了检索CSV在Javascript对象解析的数据(使用帕帕解析)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是那种尴尬,因为它看起来像它应该是如此明显要问这个问题,但我pretty弱上处理异步的问题,我如何进行混淆。

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.

我用爸爸解析( http://papaparse.com/docs.html#remote-files)来解析远程CSV。我想藏匿解析的结果,在对象以后使用。这里是我的code:

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);  

这当然会导致一个空对象被记录到控制台。在使用DataSet中的任何企图,因为,当然,DataSet对象实际上没有被code执行时间接收数据不起作用。是否有人可以帮助我重构或解释我是如何面对呢?

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?

推荐答案

有一个原因,数据集变量需要的功能外使用?以确保数据填充的最简单方法是操纵它,好,填充后右侧的完整功能的数据集。

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);

这篇关于检索CSV在Javascript对象解析的数据(使用帕帕解析)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆