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