开发者

how to search through a json response and compare a variable to existing key - value and get results of a different key - value

I want to display a polygon in a bing map. I've got this part down. I'm wondering how I would go about accessing a value from a different key in my json response once I've identified which key's sibling i'm trying to access?

I have this variable on the page:

var = 273972;

I want to match that variable to polygons.s开发者_如何学Pythonections.id[] in my json response and grab the sibling COORDS value then store that value in a new varaible.

I have jquery and _underscore.js available.

Here is my JSON

"polygons":[
    {
        "id":46327,
        "name":"first set",
        "sections":[
            {
            "id":"273971",
            "name":"202",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            },
            {
            "id":"273972",
            "name":"203",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            },
            {
            "id":"273973",
            "name":"204",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            }
        ]
    }
]


Assuming your var is named id:

var coords = _.detect(polygons[0].sections, 
                      function(val) { return val.id == id; }).coords;

See example →


I'm not sure if this is what you are looking for or not.

var jsonObj = $.parseJSON('{"polygons":[{"id":46327,"name":"first set","sections":[{"id":"273971","name":"202","coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]},{"id":"273972","name":"203","coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]},{"id":"273973","name":"204","coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]}]}]}');

var sections = jsonObj.polygons[0].sections;
for (var i = 0; i < sections.length; i++) {
    if (sections[i].id == "273972") {
        alert(sections[i].coords);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜