如何搜索json响应并将变量与现有键值进行比较,并获得不同键值的结果

时间:2011-06-01 20:57:14

标签: jquery json underscore.js

我想在bing地图中显示多边形。我把这部分放下了。我想知道如果我确定我正在尝试访问哪个密钥的兄弟,我将如何从json响应中的不同密钥访问值?

我在页面上有这个变量:

var = 273972;

我希望将该变量与我的json响应中的polygons.sections.id []匹配,并获取兄弟COORDS值,然后将该值存储在新的变量中。

我有jquery和_underscore.js可用。

这是我的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]]
            }
        ]
    }
]

2 个答案:

答案 0 :(得分:1)

假设您的var名为id

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

See example →

答案 1 :(得分:0)

我不确定这是不是你想要的。

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);
    }
}