Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
¿Cómo haría que esta salida fuera una cadena más pequeña y ordenada?

He estado jugando un poco con las API de Google, y estoy tratando de crear un comando en la terminal que me diga qué tan lejos estoy de algo y cuánto tiempo me llevaría llegar allí. El problema que tengo es que cuando ejecuto:

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

Ahora mismo está dando salida:

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

Y me gustaría que el formato de salida lo muestre como:

 you are 225 miles or 3 hours 52 mins away

¿Cómo haría para que la salida se pareciera al segundo ejemplo proporcionado?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

response.data.rows es un objeto JSON. JSON.stringify() convierte eso en una cadena, que no desea, desea el objeto.

Si no lo encadena, puede acceder a la cadena de distancia con response.data.rows[0].elements[0].distance.text y el tiempo con response.data.rows[0].elements[0].duration.text

about 4 years ago · Juan Pablo Isaza Report

0

Puede probar esto, pero asumo que está recibiendo datos en este orden

Le sugiero que agregue cheques null también.

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

about 4 years ago · Juan Pablo Isaza Report

0

Podrías usar la siguiente línea:

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!