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

I have 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 get the value areafor the record for which it idis 11 using Javascript.

Does anyone know how to do this? This is too complicated for me - my Javascript has not advanced. If I knew the index of the record array I needed, then I could do:

var entry = json_places.places[i] 

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

Thanks in advance.

+3
source share
4 answers

Just go to your places to find the desired 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);

, , :

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

:

alert(json_places.get_place(11).area);
+1
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;
}
+3
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 that you have JavaScript 1.5 (or you don't mind pasting the code in 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;
}
0
source

Using jQuery (although this question has been answered fairly enough):

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

Cm:

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

0
source

Source: https://habr.com/ru/post/1731287/


All Articles