无法读取每个undefined -d3js的属性

时间:2017-04-25 16:53:54

标签: javascript d3.js

我正在尝试使用d3js(https://bl.ocks.org/mbostock/raw/4339083/)绘制图表。这是有问题的代码:

d3.json("/MyController/MyAction", function (error, flare) {
    if (error) throw error;

    console.log(flare);

  root = flare;
  root.x0 = height / 2;
  root.y0 = 0;

  function collapse(d) {
    if (d.children) {
      d._children = d.children;
      d._children.forEach(collapse);
      d.children = null;
    }
  }

  root.children.forEach(collapse);
  update(root);
});

行:

  root.children.forEach(collapse);

  d._children.forEach(collapse);

给出错误,因为没有定义崩溃。我收到错误是因为我的JSON对象不正确吗?感谢。

这是我的控制台日志:

{"name":"Country","children":[{"name":"City","children":[{"name":"County","children":[{"name":"Child1","size":2},{"name":"Child2","size":2},{"name":"Child3","size":2}]}]}]}

你能告诉我这有什么问题吗?

2 个答案:

答案 0 :(得分:0)

您从其他地方收到错误,您发布的代码有效:

var height = 10;
var root = {
  "name": "Country",
  "children": [{
    "name": "City",
    "children": [{
      "name": "County",
      "children": [{
        "name": "Child1",
        "size": 2
      }, {
        "name": "Child2",
        "size": 2
      }, {
        "name": "Child3",
        "size": 2
      }]
    }]
  }]
}

root.x0 = height / 2;
root.y0 = 0;

function collapse(d) {
  if (d.children) {
    d._children = d.children;
    d._children.forEach(collapse);
    d.children = null;
  }
}

root.children.forEach(collapse);
console.log(root);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

答案 1 :(得分:0)

奇怪的是,当我在.json文件中保存相同的JSON时,它有效......