Zak Zak - 4 years ago 148
Javascript Question

jQuery JSON getting nested value

I haven't dealt a lot with JSON strings in JavaScript and despite my research I can't figure my way around this simple problem. Here is my issue:

my JSON

result
:

[{
"Id": "7884",
"name": "Some Name",
"location": {
"distance": 3.2988,
"geoCode": {
"latitude": "Y",
"longitude": "X"
},
"address": {
"street": "14706 E Example Ave.",
"state": "CA",
"city": "Hollywood",
"country": "USA",
"postalCode": "99999"
}
}
}]


Now I parse and iterate

var obj = JSON.parse(result);


alert(obj[0].Id);


This works great for higher level parts of the string.

However I don't know how to get into the "address" section of the string. I tried
obj[0].address.street
,
obj[0].address[street]
and even
obj[0].address[0]
to no avail.

Can someone direct me to the proper way to dig down to
street
level?

Answer Source

You should pass through location object since the address is inside it :

obj[0].location.address.street

Hope this helps.


var obj =[{
    "Id": "7884",
    "name": "Some Name",
    "location": {
        "distance": 3.2988,
        "geoCode": {
            "latitude": "Y",
            "longitude": "X"
        },
        "address": {
            "street": "14706 E Example Ave.",
            "state": "CA",
            "city": "Hollywood",
            "country": "USA",
            "postalCode": "99999"
        }
    }
}];

$('#result').text(obj[0].location.address.street);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='result'></span>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download