Katserbot Katserbot - 3 months ago 8
Javascript Question

Accessing Child in JSON Object

I have a JSON

{
"destination_addresses" : [ "14 Mission St, San Francisco, CA 94105, USA" ],
"origin_addresses" : [ "23 Mission St, San Francisco, CA 94103, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1.3 mi",
"value" : 2060
},
"duration" : {
"text" : "7 mins",
"value" : 444
},
"duration_in_traffic" : {
"text" : "6 mins",
"value" : 344
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}


I have been attempting to access the "text" value of duration_in_traffic and to store that value into a variable. For some reason I am getting the value to be undefined.

var hold = JSON.parse(body.rows.elements.duration.text);


Why cannot I access the child like this?

Answer

You have nested arrays, so you need to access the elements in the arrays by their index.

var hold = body.rows[0].elements[0].duration_in_traffic.text;
Comments