D3.js moving from tsv to json with nested array

冷暖自知 提交于 2019-12-12 20:41:44

问题


I am learning d3.js by following tutorials and trying to read example available (thanks mike).

In this example: http://bl.ocks.org/mbostock/3884955, I have trouble understanding how to move from a tsv to a nested json. I have the json and it is working if the data is not nested (see at the bottom). I have modified the code from:

   d3.tsv( "d3-multi-series-line-chart-data.tsv", function( error, data ) {
          color.domain( d3.keys( data[0] ).filter( function( key ) {
                return key !== "date";
          } 
));
...

to:

d3.json( "d3-multi-series-line-chart-data.json", function( error, data ) {
           color.domain( d3.keys( data[0] ).filter( function( key ) {
                return key !== "date";
           } 
));
...

[edit] I have the gut feeling the modification needed lies within the following piece of code:

var cities = color.domain().map(function(name) {
  return {
    name: name,
    values: data.map(function(d) {
      return {date: d.date, temperature: +d[name]};
    })
  };
});

But I failed to see how to access each city's temperature on the modified json. [/edit]

I have tried to call the key temperature, but to no avail. I have looked at a few example over here and at the documentation, but I feel stupid for not understanding. So if someone could be nice enough to show me, that would be very much appreciated.

Currently the json structure is as follow:

[
   {
      "date":"20111001",
      "New York":"63.4",
      "San Francisco":"62.7",
      "Austin":"72.2"
   },
   {
      "date":"20111002",
      "New York":"58.0",
      "San Francisco":"59.9",
      "Austin":"67.7"
   },
   {
      "date":"20111003",
      "New York":"53.3",
      "San Francisco":"59.1",
      "Austin":"69.4"
   },
   ...
]

What I want is the following:

[
   {
      "date":"20111001",
      "temperature":{
         "New York":"63.4",
         "San Francisco":"62.7",
         "Austin":"72.2"
      }
   },
   {
      "date":"20111002",
      "temperature":{
         "New York":"58.0",
         "San Francisco":"59.9",
         "Austin":"67.7"
      }
   },
   {
      "date":"20111003",
      "temperature":{
         "New York":"53.3",
         "San Francisco":"59.1",
         "Austin":"69.4"
      }
   },
   ...
 ]

回答1:


To start with, the easiest thing to do is to simply convert your nested structure to something the example can work with. The code would look something like this.

var flat = [];
json.forEach(function(d) {
  d.temperature.forEach(function(e) {
    e.date = d.date;
    flat.push(e);
  });
});

On a general note, I would advise having your numbers as numbers in the JSON and not strings (i.e. without the quotes).



来源:https://stackoverflow.com/questions/19502421/d3-js-moving-from-tsv-to-json-with-nested-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!