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