0

<!DOCTYPE html>

<html>

<head>

    <title>Practice</title>

</head>

<body>


    <script>
        const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';

        const cities = [];

        fetch(endpoint)
            .then(blob => blob.json())
            .then(data => cities.push(...data));


        console.log(cities)
        console.log(cities[0])
        console.log(cities[0].city)
    </script>
</body>

</html>

The code is supposed to get data from JSON, push it into the cities array with spread operator then play with the cities array to access its contents.

But I run this code on a browser and open console, console.log(cities) shows an array of objects. But when I'm trying to access the object inside, it returns undefined. I tried to copy property path on chrome console and it shows [0].city.

I expect a result of

{city: 'New York', growth_from_2000_to_2013: '4.8%', latitude: 40.7127837, longitude: -74.0059413, population: '8405837', …}

when I run console.log(cities[0])

and get

'New York'

when I run console.log(cities[0].city)

unfortunately it shows

undefined

and

index.html:26 Uncaught TypeError: Cannot read properties of undefined (reading 'city') at index.html:26:31

respectively.

1 Answer 1

0

fetch is an asynchronous operation, meaning by the time the cities is populated your code has already executed the console.log statement. To fix this make the following change:

<!DOCTYPE html>

<html>

<head>

    <title>Practice</title>

</head>

<body>


    <script>
        const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';

        const cities = [];

        fetch(endpoint)
            .then(blob => blob.json())
            .then(data => cities.push(...data))
            .then(() => {
                  console.log(cities)
                  console.log(cities[0])
                  console.log(cities[0].city)
             });
    </script>
</body>

</html>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.