Requesting data from a JSON array of objects leads to an undefined result

<!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 goal of this code is to retrieve data from a JSON file, add it to the cities array using the spread operator, and then interact with the contents of the cities array.

Upon running this code in a browser and checking the console, console.log(cities) displays an array of objects. However, attempting to access the object within the array results in undefined values. When inspecting the property path on the Chrome console, it indicates [0].city.

The expected outcome should be

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

when executing console.log(cities[0])

which should yield

'New York'

when running console.log(cities[0].city)

Unfortunately, it currently shows

undefined

followed by

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

respectively.

Answer №1

fetch is a process that occurs asynchronously, which means that the console.log statement in your code has already executed before the "cities" variable is populated. To resolve this issue, you can implement the following modification:

<!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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing filters dynamically from ng-repeat in Angular

I am currently using ng-repeat to display a list of staff members: <div ng-repeat="user in staff | profAndDr"> There is also a custom filter called 'profAndDr' that only shows people with the titles "Dr." and "Prof.": app.filter('pr ...

Ensuring the image is properly sized to fit the screen and enabling the default zoom functionality

I am looking to achieve a specific behavior with an image, where it fits the viewport while maintaining its aspect ratio and allowing for zooming similar to how Chrome or Firefox handle local images. Here are the details of my project: The image I have is ...

Disabling Express BodyParser for handling file uploads in Node.js

When developing my web application with Node.js + Express, I've found the connect BodyParser to be incredibly useful. However, I'm looking for a way to have more control over multipart form-data POSTS so that I can stream the input directly to an ...

Predefined date range is set by the OnChange event of Daterangepicker.js

I'm currently exploring the implementation of the onChange event in this select picker with the assistance of the daterangepicker.js library. Unfortunately, after conducting a thorough search on the DateRangePicker repository, I was unable to find any ...

Whenever the cursor hovers over, the DIV above the iframe flickers

I'm having trouble placing a social button on top of an iframe that contains a YouTube or Vimeo video. The social buttons are located within a div container, which reveals or hides the content with JavaScript. However, I'm experiencing a blinking ...

Displaying the Status of a Script that is Running Asynchronously

My script takes around 5 minutes to complete and sends an email with a file attachment once finished. The entire process happens on a single PHP page without using AJAX. I want the front end to handle form submission seamlessly, processing the request in ...

What could be the reason behind needing to use JSON.parse() on my AJAX response at times?

I am experiencing some inconsistency in how my client-side jQuery processes JSON ajax responses from server-side PHP. Below are examples of two different ajax calls I have: function checkOrders() { $.ajax({ type: "POST" , url:"/serv ...

Using ReactJS to create different behavior for checkboxes and rows in tables with Material-UI

I am looking to customize the functionality of checkboxes and table rows. Currently, clicking on a row also clicks the checkbox, and vice versa. What I would like to achieve is for clicking on a row to trigger a dialogue box, and for clicking on the chec ...

What is the best way to toggle a sticky footer menu visibility using div elements with JavaScript instead of relying on pixel measurements?

Just wanted to mention that I'm pretty new to this, so if I use the wrong terms, I apologize in advance. I am trying to replicate Morning Brew's sticky footer opt-in form (check it out here). However, the code I have now only tracks pixels. Is t ...

Struggling with converting Golang JSON struct to lowercase

Describe the struct I am using: type Credentials struct { Username string `json:"username"` Password string `json:"password"` ApplicationId string `json:"application_id"` ApplicationKey string `json:"application_key"` } I hav ...

Utilize React-router to display child components on the webpage

Recently, I've encountered some challenges with this code. I have a component that takes in a child as a prop, which is meant to serve as the foundation for all the pages I am hosting. Base.jsx : import React from 'react'; import PropTypes ...

What is the best way to map keys to values in JMeter when the values are generated as output and then save them in a MongoDB database?

When using the debug sampler, keys like Price_1, Price_2, etc. are displayed. However, when I try to store in MongoDB, only values are being saved. How can I properly assign and store both keys and values in MongoDB? Thank you in advance! ...

Linking promises together and including extra information to be passed along with the following promises

Can you help me with chaining promises and adding extra data to be returned in the .then, while also making another API request in the process? I've come across similar discussions, but none that show how to include additional data and carry it throug ...

Utilize a React function to incorporate an external link

Looking to create a link to Twitter using the href attribute but encountering errors with the atag. Is there an alternative method I could use? In essence, I want to have a picture on my homepage that, when clicked, redirects the user to Twitter. I' ...

Provide personalized files according to individual preferences

I am looking to create a website that can generate a custom file based on user input. For example, if it's a story, I want the user's name to be inserted into the text where there is a designated variable for swapping, but this customization shou ...

What is the best way to extract message data using discord.js?

Discord.js is an API designed for developers to create plugins for Discord, a popular communication platform. You can find the API code written in JavaScript by visiting https://github.com/hydrabolt/discord.js/ On Discord, users interact on servers where ...

Ways to attach the retrieved HTML content?

When working with Django views, I often come across the need to return data using context. For example: context['foo'] = 'bar' return render_to_response('test.html', context_instance=context) In this scenario, test.html is n ...

A comparison between the Composition API and traditional Plain JavaScript syntax

I'm currently exploring the necessity of utilizing the 'new' Vue Composition API. For instance, take the following component extracted from their basic example: <template> <button @click="increment"> Count is: {{ ...

HTML Navigator encountering Javascript Anomaly

Here is the code snippet I'm working with: driver = new HtmlUnitDriver(); ((HtmlUnitDriver) driver).setJavascriptEnabled(true); baseUrl = "http://www.url.com/"; driver.get(baseUrl + "/"); ... However, whenever I ...

Working with session ID and Ajax in JavaScript

Recently, I've discovered that my website is experiencing issues on various versions of Internet Explorer. Despite conducting thorough research, it appears that cookies are not functioning properly when accessed through IE, although they work without ...