Imo
Imo

Reputation: 1475

d3.js problems with reading dataset

I am trying to solve this error since 2 days now not sure any more how to solve this. I get this error white trying to add data to the visualization

Uncaught TypeError: Cannot read property 'length' of undefined

This seems to be related to dataset. But no matter what I do I get this error if I console.log dataset outside checkit function(see below) it returns undefined.

Data

[ {
    "Continent":"Asia.Oceania",
    "Country_Names":"Viet Nam",
    "Total":142.9
  },
  {
    "Continent":"Asia.Oceania",
    "Country_Names":"Yemen",
    "Total":20
  },
  {
    "Continent":"Misc",
    "Country_Names":"World marine bunkers",
    "Total":602.2
  },
  {
    "Continent":"Misc",
    "Country_Names":"World aviation bunkers",
    "Total":477.8
  }
]

code

var svg_0 = d3.xml("drawing.svg", "image/svg+xml", function(xml) {
    var importedNode = document.importNode(xml.documentElement, true);
    d3.select("#viz").node().appendChild(importedNode);



var dataset;

function checkIt(data){
for (var i in data) {
            var data_clean;
            data_clean = data[i].Total
            dataset = data_clean
            console.log(dataset) //returns data
        }

        }
    console.log(dataset)//returns undefined


    d3.json("data.json", checkIt);


    var svg =  d3.select("#level_0")
                .selectAll("path")
                .data(dataset)
                .enter()
    });

Upvotes: 0

Views: 398

Answers (1)

shershen
shershen

Reputation: 10003

d3.json("data.json", checkIt); is an asynchronous operation (check syntax here for example). In short it means that at some point of your code execution dataset variable is literally undefined yet. Then, later it is defined, but it's too late.

This means that you need to be sure that dataset is defined when starting using it. For example you can move usage to checkIt callback like so:

  var dataset;
    function checkIt(data){
     var data_clean = []; //prepared variable for clear data
    for (var i in data) {
      data_clean.push(data[i].Total);
      }
  //move initialisation here, to be sure dataset is there
  var svg =  d3.select("#level_0")
               .selectAll("path")
               .data(data_clean);  
  }
//other code here...
d3.json("data.json", checkIt);
//other code here...

Upvotes: 2

Related Questions