访问嵌套数据

时间:2013-04-28 23:50:00

标签: javascript json d3.js

我目前正在调用两个json请求到我的文件中:

d3.json("path/to/file.json", function(error, json) {

   d3.json("path/to/file.json", function(error, json2) {

   });
});

json 2的结构是这样的:

[ 
  { "city" : "LA",
    "locations" : [ { "country" : "USA", "x" : 0, "y" : 0 } ] 
  }, 
  { "city" : "london",
    "locations" : [ { "country" : "UK", "x" : 0, "y" : 0 } ]
  }
  ... 
]

目前我正在尝试访问x& y值为json2。但是,我遇到的问题是我希望同时使用json和amp;我的变量中的json2:

var node = svg.selectAll("a.node")
 .data(json.cars)
 .enter().append("a")
 .attr("class", "node")
 ;

在这里,我希望将xson2称为x&仅限位置

node.attr("transform", function(d, i) {
    return "translate(" + d.x + "," + d.y + ")";
});

node.append('path') 
    .attr("d", d3.svg.symbol().type(function(d) { return shape [d.name]; }).size(120))
    .style("fill", function(d) { return colors [d.name]; } );

我要求的是什么......我尝试了以下内容:

node.attr("transform", function(d,i) {
    return "translate(" + json2.locations[d].x + "," + json2.locations[d].y + ")";
});

但没有运气。任何帮助都会很棒 - 谢谢。

1 个答案:

答案 0 :(得分:0)

您需要先选择阵列中包含位置的其中一个对象。这些位置也是一个对象数组,因此您需要一个索引来访问它。试试这个以获得LA,USA x变量。

json2[0].locations[0].x
相关问题