JQuery $ .each only returns first JSON element

I have a JSON object like:

{
    "mesta": [
        {
            "latlng": [49.094046,15.893415],
            "nazev": "Město Jaroměřice nad Rokytnou"
        },
        {
            "latlng": [49.44119,18.09461],
            "nazev": "Obec Vidče"
        },
        {
            "latlng": [49.5047,17.10139],
            "nazev": "Obec Smržice"
        }
    ],
    "orp": [
        {
            "latlng": [49.2156,15.87819],
            "nazev": "Město Třebíč (ORP)"
        },
        {
            "latlng": [49.457623,18.142622],
            "nazev": "Město Rožnov pod Radhoštěm (ORP)"
        }
    ]
}

      

When I try to iterate over the object, I only get the first item (mesta) in alert mode. According to jsonlint, the syntax is correct. Did I miss something?

function loadMarkers() {
    $.getJSON('data.json', function(data) {

        $.each(data,function(index,obj) {
                alert(index);
        });
    });
}

      

+3


source to share


4 answers


The problem is the response from the server, not your JavaScript. I ran the following code in the console on your page:

$.getJSON('data.json', function(data) { 
    console.log(data); 
});

      

The result looks like this:



enter image description here

As you can see, there is only one property in the returned object ( mesta

, an array with three elements).

You can confirm this by visiting the file directlydata.json

.

0


source


Please check your answer. $. everyone works fine .



0


source


The problem is not your JSON object but the $ .each function, I was able to iterate over both keys in the above data here http://jsfiddle.net/d4udts/N2C3j/

the problem seems to be related to your getJSON call. I doubt your call only returns the first item, you debug the code and see what data is being retrieved by json to call

0


source


You select every object that has an array of objects.

The solution would probably be that you put each in each or not use jQuery.each but simple for the likes ... (since the returned object is called data)

for(obj in data){
    for(entry in data[obj]){
    {
       console.log(entry)
       ....
    }
}

      

0


source







All Articles