0

I am importing some data and I would like to use those data outside of the function importing them. I tried to follow examples as illustrated in this answer (response1, response2, response3, response4) and others but I am still not capable to understand how to do it. In my most successful attempts I tried 1) to create a global variable, 2) to have the function returning the data itself (this second attempt is embedded in the code below but commented out). But I am still not able to access the data outside of the scope of the function importing them. Any help will be appreciated. Below is my code with attempts and return values included. Thank you very much!

    var dataset; // a global
    d3.json("data.php", function(error, jsonData) {
    //var dataset = d3.json("data.php", function(error, jsonData) {
         if (error) return console.warn(error);
         jsonData.forEach(function (d) {
             d['id'] = d['id'];
             d['transaction_id'] = +d['transaction_id'];
             d['ddmmyy'] = d3.time.format("%Y-%m-%d").parse(d['ddmmyy']);
             d['amount'] = +d['amount'];
        }) // end: dataset.forEach
        dataset = jsonData;
    //  return jsonData;
    }); // end: d3.json

    // return values for attempt 1 with var dataset; (...)
    console.log(dataset[0]); // returns: TypeError: dataset is undefined
    var expensesByName = d3.nest()
      .key(function(d) { return d['transaction_id']; })
      .entries(dataset); 
    // typing expensesByName on console returns: undefined 

    // return values for attempt 2 with: var dataset = d3.json(...)
    //console.log(dataset[0]); // returns: undefined
    // var expensesByName = d3.nest()
    //   .key(function(d) { return d['transaction_id']; })
    //   .entries(dataset); 
    // typing expensesByName on console returns: empty array
Community
  • 1
  • 1
HelloWorld
  • 697
  • 10
  • 16
  • The callback function that changes `dataset` value is invoked _after_ `console.log` line, even though it's placed earlier in your script. The question linked explains this (and various workarounds) in details. – raina77ow Mar 04 '16 at 11:14
  • That solves it indeed. I did not know about the asynchronous nature of JavaScript. Thank you! – HelloWorld Mar 04 '16 at 11:23

0 Answers0