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

143
Views
Obtener datos de la API y crear un objeto

Tengo una matriz que contiene 5 ciudades y quiero detalles meteorológicos de estas cinco ciudades. Apliqué bucle para long y lat que obtuve, pero me quedé atascado. ¿Cómo aplicaría long y lat para obtener los detalles sobre las ciudades para crear objetos, por ejemplo cities={London:{temp:xyz}} ? cities={London:{temp:xyz}} .

 var cities = { Phoenix: {}, ... }; function getData() { var city = ['London', 'Phoenix', 'Chicago', 'Texas']; for (var i = 0; i < city.length; i++) { var api = 'http://api.openweathermap.org/geo/1.0/direct?q=' + city[i] + '&appid=4dad41fdcc37b40dd07e3e1638f24b81'; // var api = 'http://api.openweathermap.org/data/2.5/weather?lat='+lat[i]+'&lon='+lon[i]+'&appid=4dad41fdcc37b40dd07e3e1638f24b81' fetch(api).then(function(response) { var data = response.json(); return data; }).then(function(data) { cities.Phoenix.temp = Math.floor(data.main.temp); }); } } getData();
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Debe usar la notación de corchetes para obtener la referencia a la ciudad en su objeto. cities[city[i]].temp . El problema que tendrá es el infame bucle for donde el i será diferente debido a la llamada asíncrona.

Personalmente, lo convertiría en una función y lo llamaría. Map() simplifica el ciclo.

 var cityNames = ['London', 'Phoenix', 'Chicago', 'Texas']; var cities = {}; function fetchCity(city) { var api = '//example.com/q=' + encodeURIComponent(city); return fetch(api) .then(function(response){ return response.json(); }).then(function (data) { cities[city] = cities[city] || {}; cities[city].temp = Math.floor(data.main.temp); return data; }); } function getData(callback) { var fetchCalls = citiesNames.map(fetchCity); Promise.all(fetchCalls).then((values) => { callback(values); }); } getData(function (values) { console.log('All Loaded', values); });
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!