0

我需要准确地循环遍历我的 json 数组以匹配位置 id 和 d3 对象 id。

这是数组的片段(生成的 ruby​​ on rails ):

{
    "name": "Test",
    "locations": [{
        "city_id": 1,
        "x": 0,
        "y": 0
        }, {
        "city_id": 2,
        "x": 0,
        "y": 0
        }, {
        "city_id": 3,
        "x": 0,
        "y": 0
        }, {
        "city_id": 118,
        "x": 0,
        "y": 0
        }, {
        "city_id": 117,
        "x": 0,
        "y": 0
        }, 
    ],
    "city": [{
        "id": 118,
        "name": "London"
        }, {
        "id": 117,
        "name": "New York"
        }, {
        "id": 1,
        "name": "Miami"
        }, {
        "id": 3,
        "name": "Duabi"
        }, {
        "id": 2,
        "name": "Hong Kong"
        }
    ]
}

要收集 x 和 yi 的值,请使用拖放功能。当一个物体掉落时,我会发送一个帖子来更新 x 和 y 值的位置。但是,它会将更新发送到正确的 id,因为我的循环不够具体。

所以现在我必须找到一种方法来收集城市位置并将它们与 d3 对象/城市匹配。所以我这样循环:

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

但这只是通过数组而不匹配任何东西。因此,我基本上希望我的循环通过并查看 ids 是否相关,然后将该位置分配给相关的 d3 对象。因此,如果拖放城市 id: 118 位置 city_id:188 应该更新而不是 city_id:1 这是问题所在。

这可能吗。

提前致谢

4

1 回答 1

0

你的意思是这样的?

//i don't know where is it from
given_id = 118;

for(i=0;i<json.locations.length;i++) {
    var id = json.locations[i].city_id;
    if(id==given_id) {
        var x = json.locations[i].x;
        var y = json.locations[i].y;
        console.log(x+","+y);
        //do something with x and y
    }
}

http://jsfiddle.net/LyQZ6/

于 2013-06-26T19:54:31.437 回答