0

results after Hello I'm trying to read JSON data from an api but it doesn't work when I try to get data from that api works fine and when I try to get the distance value I get undefined.Please help

The code

fetch('https://maps.googleapis.com/maps/api/distancematrix/json?units=meter&origins=Gurd%20Shola%201%20Station,%20Addis%20Ababa&destinations=Bole%20Medhane%20Alem%20Church,%20Addis%20Ababa&key=API_KEY')
  .then(response => {
    return response.json()
  })
  .then(data => {
// Work with JSON data here
console.log(data.rows.elements.distance.value)
 })
  .catch(err => {

 })

the result from the web is just like this

{
   "destination_addresses" : [ "Addis Ababa, Ethiopia" ],
   "origin_addresses" : [ "Addis Ababa, Ethiopia" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "6.4 km",
                  "value" : 6386
               },
               "duration" : {
                  "text" : "15 mins",
                  "value" : 901
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}
2
  • Rows property is an array of objects so try to use loop and access the property. Commented Dec 19, 2019 at 6:56
  • 1
    that's because 'elements' is an array and to fetch any particular value you need to access it using data.rows[0].elementes[0].distance.value or run a loop to access every value. Commented Dec 19, 2019 at 6:57

1 Answer 1

2

Change data.rows.elementes.distance.value to data.rows[0].elements[0].distance.value..

Check for typo here it is elements and not elementes..

Also rows and elements is an array and if you need to get the distance then you need to get it like rows[0].elements[0].distance ..

const data = {
   "destination_addresses" : [ "Addis Ababa, Ethiopia" ],
   "origin_addresses" : [ "Addis Ababa, Ethiopia" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "6.4 km",
                  "value" : 6386
               },
               "duration" : {
                  "text" : "15 mins",
                  "value" : 901
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

console.log(data.rows[0].elements[0].distance);

Sign up to request clarification or add additional context in comments.

3 Comments

Typos, they're inevitable.
@haptomee, try like console.log(data.rows[0].elements[0].distance);..
@haptomee, As rows is also array you need to put rows[0] as well.. Updated the answer..

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.