开发者

Tricky Javascript: how to retrieve value from json dict inside array inside dict :)

I've got a json file included in my javascript that defines a variable that looks like this:

var places_json = {
  "count": 13476,
  "places": [{
      "area": "London",
      "county": "STS",
      "lat": 52.300151820000004,
      "lon": -2.36665606,
      "code": "7567",
      "id": 1
    },
    {
      "area": "Sheffield",
      "county": "STS",
      "lat": 51.33648680000003,
      "lon": 0.98861179000000001,
      "code": "9919",
      "id": 6
    },
    {
      "area": "Huxton",
      "county": "STS",
      "lat": 53.27483902,
      "lon": -1.0146250700000001,
      "code": "9953",
      "id": 11
    },
  ]
}

And I want to retrieve the value of area for the entry whose id is 11, using Javascript.

Does anyone know how to do this? It's too hard for me - my Javascript is not that advanced. If I knew the array index of the entry that I need, then I could do:

var en开发者_运维知识库try = json_places.places[i] 

but I don't know it, unfortunately, just the value of id (which is unique).

Thanks in advance.


function findAreaById(placesArray, id) {    
    var place = null;
    for (var i = 0, length = placesArray.length; i < length; i++) {
        place = placesArray[i]; 
        if (place.id === id) {
            return place.area;
        }
    }
    return null;
}


Simply loop through your places to find the proper item.

var area = null;
for(var i = 0; i < json_places.places.length; i++) {
  if(json_places.places[i].id == 11) {
    area = json_places.places[i].area;
    break;
  }
}

alert(area);

If you want a function to do it for you, you can run the following:

json_places.get_place = function(id) {
   return (function(id) {
             for(var i = 0; i < this.places.length; i++) {
               if(this.places[i].id == id) {
                 return this.places[i];
               }
             }

             return null;
           }).apply(json_places, id);
}

Then you can simply do the following:

alert(json_places.get_place(11).area);


function get_area(places_json, id) {
    for (var i = 0; i < places_json.places.length; i++) {
        if (places_json.places[i].id === id) {
            return places_json.places[i].area;
        }
    }
}

Also, if you know you have JavaScript 1.5 available (or you don't mind pasting in the code at https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter ...), and especially if you know LINQ:

function get_area(places_json, id) {
    return places_json.places.filter(function (place) { place.id === id; })[0].area;
}


Using jQuery (even though this question has been sufficiently answered):

var area = null;
$.each(places_json.places, function() {
    if(this.id == 11) {
        alert("Area is " + this.area);
        area = this.area;
        return false;
    }
});

See:

http://api.jquery.com/jQuery.each/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜