简体   繁体   中英

loop through Object in Javascript get from PHP

Hello I have a PHP script that returns the following JSON :

[
    {
        "zone_name": "1st_zone"
    },
    {
        "coordinates": [
            "51.56256,-0.37903",
            "51.50789,-0.19913",
            "51.58475,-0.06729",
            "51.61461,-0.19638",
            "51.5711,-0.28152"
        ]
    },
    {
        "zone_name": "2nd_zone"
    },
    {
        "coordinates": [
            "51.56256,-0.37903",
            "51.50789,-0.19913",
            "51.58475,-0.06729",
            "51.61461,-0.19638",
            "51.5711,-0.28152",
            "51.57707,0.11398",
            "51.48651,0.12497",
            "51.56939,0.28427"
        ]
    }
]

In Javascript I'm doing an AJAX call like that :

$.ajax({
        type: "POST",
        cache: false,
        url: "load_zone.php",   
        dataType: 'json',
        success:function(response){
            for(var i =0; i<response.length; i++){
                console.log(response[i]);
            }
        },
        error:function(){
        }
    }); 

I get this result in console :

Object { zone_name="1st_zone"}
Object { coordinates=[5]}
Object { zone_name="2nd_zone"}
Object { coordinates=[8]}

How can I print each zone_name and coordinates separately?

Thanks

for(var i =0; i<response.length; i++){
   if(i%2 === 0) console.log(response[i].zone_name);
   else console.log(response[i].coordinates); 
  // console.log(response[i].zone_name || response[i].coordinates); //one liner
}

This will give you the respective zone names and coordinates. Your current JSON has an array of objects which list the zone names and coordinates as successive elements of the array.

But you should try to change your json to look something like this:

[
    {
        "zone_name": "1st_zone"
        "coordinates": [
            "51.56256,-0.37903",
            "51.50789,-0.19913",
            "51.58475,-0.06729",
            "51.61461,-0.19638",
            "51.5711,-0.28152"
        ]
    }
...
]

Which will mean that the array would contain objects representing a zone with its coordinates. Which can then be accessed like response[i].zone_name and response[i].coordinates .

do like this:

$.each(data,function(index,item){

    console.log(item);
    $.each(item,function(index1,item1){
    console.log(item1);
    });

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM