Evil2
Evil2

Reputation: 17

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

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:

you are 225 miles or 3 hours 52  mins away

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

Upvotes: 0

Views: 54

Answers (3)

2pichar
2pichar

Reputation: 1378

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

Upvotes: 1

Shivam
Shivam

Reputation: 3642

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

Upvotes: 1

Quasipickle
Quasipickle

Reputation: 4498

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

Upvotes: 1

Related Questions