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

Time:03-30

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, DC&destinations=New York City, NY&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:

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!

CodePudding user response:

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);

CodePudding user response:

response.data.rows is a JSON object. JSON.stringify() converts that into a string, which you don't want - you want the object.

If you don't stringify it, you can access the distance string with response.data.rows[0].elements[0].distance.text, and the time with response.data.rows[0].elements[0].duration.text

CodePudding user response:

You could use the following one-liner:

var data = [{"elements":[{ "distance": {"text": "225 mi", "value": 361918}, "duration": {"text": "3 hours 52 mins", "value": 13938}, "status": "OK"}]}];
console.log(`you are ${ data[0].elements[0].distance.text} or ${data[0].elements[0].duration.text} away`);

  • Related