在Javascript中为d3.js创建来自URL的多字节JSON

时间:2018-05-12 09:41:36

标签: javascript json d3.js

我有以下问题。我有一个可用于URL的平面json,我希望在d3.js图表​​中使用Javascript作为嵌套JSON加载。我的代码如下:

d3.json('http://88.99.13.199:3000/measures', function(err, mydata) { 
   mydata.forEach(function(val) { 
      var measuresdata=[];
      var ent = [];
      var plir = [];
      var subm = [];
      ent.push({
          name: "entaxeis",
          size: val.entaxeis
      });
      plir.push({
          name: "pliromes",
          size: val.pliromes
      });
      subm.push({
          name: val.submeasure_code,
          children:{ent, plir}
      });
      measuresdata.push({
          name: val.measure_code,
          children:{subm}
      });
      console.log(measuresdata);
   });
   console.log(measuresdata);
}); 

我希望我的json如下:

{
   "name": "Μ01",
   "children": [
    {
     "name": "1.1",
     "children": [
      {"name": "entaxeis", "size": 456123},
      {"name": "pliromes", "size": 3812}
     ]
    }
   ]
  },
  {
   "name": "M03",
   "children": [
    {
     "name": "3.1",
     "children": [
      {"name": "entaxeis", "size": 456123},
      {"name": "pliromes", "size": 3812}
     ]
    },
   ]
 }
(..)

等等。这是一个难题,所以任何帮助都会很棒!

1 个答案:

答案 0 :(得分:2)

由于您添加了d3.js标记,我认为最简单的解决方案是使用d3.nest()函数按键分组,然后在结果数组上使用map函数创建所需的结构:

var nested = d3.nest()
  .key(function(d) { return d.measure_code; })
  .entries(mydata)
  .map(function(measure) {
    return {
      name: measure.key,
      children: measure.values.map(function(submeasure) {
        return {
          name: submeasure.submeasure_code,
          children: [
            { name: "entaxeis", size: submeasure.entaxeis },
            { name: "pliromes", size: submeasure.pliromes }
          ]
        };
      })
    };
  });