Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

59
Visualizações
Can't index items within array

Okay, I have been struggling with this for hours but I still can't figure this out so if anyone has the solution, thank you!!!

In my code below, I am fetching data from my API (which then fetches data from the Google Places API Nearby Search. Now the API returns a list of about 20 different locations. For each location, I've created an object containing the data only I want. Then, I simply push this data to the business array.

(The fetch is in a loop because the Google API only allows you to search for one type of building (cinema, bookstore, bowling_alley, etc...) at a time so I've put the fetch in a loop to loop over all of the different types of buildings I want data of)

Now, my issue is that if I try to get the first business of the businesses array businesses[0], it returns undefined. However, what I find even stranger is if I log the businesses array to the console, it displays all the of the business. I have no idea why this is happening so if anyone knows, please do tell and I'll be very grateful.

getNearbyPlaces = (latitude, longitude, radius, types) => {
  const businesses = [];
  types.forEach(async (type) => {
    await fetch(`${url}/google/places/nearbysearch?lat=${latitude}&lng=${longitude}&rad=${radius}&type=${type}`, {
      method: 'GET',
      body: null
    }).then(response => {
      if (response.ok) {
        return response.json();
      }
      throw new Error('ERROR: Google-Api Nearby Places - response not okay');
    }, networkError => console.log(networkError.message)
    ).then(jsonResponse => {
      if (jsonResponse.results) {
        jsonResponse.results.forEach(result => (
          [...businesses].push({
            id: result.place_id,
            name: result.name,
            address: result.vicinity,
            categories: result.types,
            rating: result.rating,
            reviewCount: result.user_ratings_total
          })
        ))
      }
    });
  });
  console.log(businesses); // logs the list of bsuiness
  console.log(businesses[0]); // logs undefined 
}

Below is the image displayed to the console for when I log the businesses array and businesses[0] (Data has been blocked out for privacy reasons)

Image of what is displayed in the console after execution

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda