Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would I make this output a smaller more neat string?

So i have been messing around with googles APIs a little bit, and i am trying to create a in terminal command that tells me how far away i am from something and how long it would take to get there.
The issue that i am having is that when i run:

var axios = require('axios');

var config = {
    method: 'get',
    url: 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Washington%2C%20DC&destinations=New%20York%20City%2C%20NY&units=imperial&key=AIzaSyCbwuhNvOJQrYWnLRF6WjzJeOcnhYYfpZA',
    headers: {}
};

axios(config)
    .then(function(response) {
        console.log(JSON.stringify(response.data.rows));
    })
    .catch(function(error) {
        console.log(error);
    }); 

Right now it is outputting:

[{"elements":[{"distance":{"text":"225 mi","value":361918},"duration":{"text":"3 hours 52 mins","value":13938},"status":"OK"}]}]

And i would LIKE the output format to display it like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

you are 225 miles or 3 hours 52  mins away

How would i go about making the output look like the second supplied example?

It may be a dumb question, but any help would be greatly appreciated!

>Solution :

You can try this, but I’m assuming you are receiving data in this order

I would suggest you to add null checks as well.

let data = [{
  "elements": [{
    "distance": {
      "text": "225 mi",
      "value": 361918
    },
    "duration": {
      "text": "3 hours 52 mins",
      "value": 13938
    },
    "status": "OK"
  }]
}];

let firstElement = data[0].elements[0];

let constructedString = `You are ${firstElement.distance.text} or ${firstElement.duration.text} away`;

console.log(constructedString);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading