D
D
Dmitriy_Gultiaev2021-07-21 18:24:06
JavaScript
Dmitriy_Gultiaev, 2021-07-21 18:24:06

Accessing an existing object property but getting undefined?

Hello everyone, what's the problem:
I'm using fetch to make an API request. Here is the code:

async function getInformation() {
        let response = await fetch(`https://api.allorigins.win/get? 
        url=${encodeURIComponent('https://maps.googleapis.com/maps/api/distancematrix/json? 
        origins=Луганск&destinations=Киев&key=AIzaSyCO9I-9cmBpuwUJEdBcNe5F3AGN4iW_Dzs')}`);
        let content = await response.json();
        let data = await content.contents;

        console.log(data.rows)
    }

getInformation();


Then I get the response as JSON:

{
   "destination_addresses" : [ "Luhansk, Luhansk Oblast, Ukraine, 91000" ],
   "origin_addresses" : [ "Kyiv, Ukraine, 02000" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "830 km",
                  "value" : 830166
               },
               "duration" : {
                  "text" : "11 hours 12 mins",
                  "value" : 40349
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}


Well, when I try to access the rows property like this:
console.log(data.rows)
I get undefined, I can't figure out why

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2021-07-21
@Dmitriy_Gultiaev

Your contents is not an object, but another JSON string.

{
  contents: "{\n   \"destination_addresses\" : [ \"Kyiv, Ukraine, 02000\" ],\n   \"origin_addresses\" : [ \"Luhansk, Luhansk Oblast, Ukraine, 91000\" ],\n   \"rows\" : [\n      {\n         \"elements\" : [\n            {\n               \"distance\" : {\n                  \"text\" : \"821 km\",\n                  \"value\" : 821154\n               },\n               \"duration\" : {\n                  \"text\" : \"11 hours 32 mins\",\n                  \"value\" : 41522\n               },\n               \"status\" : \"OK\"\n            }\n         ]\n      }\n   ],\n   \"status\" : \"OK\"\n}\n"
​  status: {
​​    content_length: 530
    ​​сontent_type: "application/json; charset=UTF-8"
​​    http_code: 200
​​    response_time: 330
​​    url: "https://maps.googleapis.com/maps/api/distancematrix/json?origins=Луганск&destinations=Киев&key=AIzaSyCO9I-9cmBpuwUJEdBcNe5F3AGN4iW_Dzs"
  }
}

She needs to be parsed again
const data = JSON.parse(content.contents);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question