I've been going through Wes Bos' Javascript30 course, and have been messing with JSON and arrays.
I'm trying to figure out what's happening here.
I have a simple JSON test file that I'm fetching and pushing into an array, and an identical array created locally. When I try to console.log
the name of the first person with the local array, it works fine. But when I try to console.log
the name of the first person in the JSON fetched array, I get an error "Uncaught TypeError: Cannot read property 'name' of undefined"
JSON file:
[
{
"name":"Sean",
"Age":"23"
},
{
"name":"kev",
"Age":"23"
}
]
javascript:
const people = [];
const peopleLocal = [ {"name":"Sean", "age":"23"}, {"name":"kev",
"age":"23"}];
const endpoint = "test.json";
fetch(endpoint)
.then(blob => blob.json())
.then(data => people.push(...data));
console.log(people);
console.log(peopleLocal);
console.log(peopleLocal[0].name);
console.log(people[0].name);
console.log(people)
and console.log(peopleLocal)
returns the same array of objects. Then console.log(peopleLocal[0].name)
returns "Sean". But console.log((people[0].name)
returns the undefined
error mentioned above. Why?