0

I am trying to access specific values from a JSON file by the key lat as I loop through each record. However I have been getting undefined result as I printed them.

JSON

[{"pid":4317129482,"lat":"51.5078","lon":"-0.10467","coords":{"x":-0.10467,"y":51.5078},"points":{"x":-0.10467,"y":51.5078}},
{"pid":4356791546,"lat":"51.522","lon":"-0.101773","coords":{"x":-0.101773,"y":51.522},"points":{"x":-0.101773,"y":51.522}},

The JSON is stored in data

Code attempted

$.each(data, function(key, value){  
                            if (key == "lat") {
                                console.log(value)
                            }

OR

$.each(data, function(item){    
                            console.log(item.lat)
}

3 Answers 3

1

If the JSON you have posted is proper, its an array of objects. So $.each(data,function(key,val){}) would return index and the object i.e. key would be 0,1,2 and value the object.

To access

"lat":"51.522"

you have to do

$.each(data,function(key,val){
    //val here is your object. For each object in the array you have to loop again 
    $.each(val,function(k,v){
        //now since val is an object looping through it will return your key-value pairs
        if(k == 'lat'){
        //Do something
        }
    })
})
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

$.each(data, function(key, value){
   console.log(value.lat); 
});

Comments

0

If it helps change the argument names to be more of an indication of what you are looping over with $.each

For array something like:

$.each(arr, function(index, arrayElement){

})

For object

$.each(obj, function(objKey, propertyValue){

});

When uncertain what's inside the loop use console.log([index, arrayElement]) so you can inspect it in browser dev tools console

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.