Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
Fetching data from API and creating an object

I have an array which contains 5 cities and I want weather details of these five cities I applied loop for long and lat I got but I got stuck that how would I apply long and lat to get the details about the cities to create object e.g. 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 Respuestas
Responde la pregunta

0

You need to use bracket notation to get the reference to the city in your object. cities[city[i]].temp. The problem you will have is the infamous for loop where the i will be different because of the asynchronous call.

Personally I would make it a function and call it. Map() simplifies the loop.

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda