I'm trying to learn JavaScript and I think I'm running into a problem with scope. I'm trying to access an array created in a then{}
, but I receive this error (testJS.js:43 Uncaught TypeError: Cannot read property '1' of undefined
) when I try to console.log the array value outside of the then{}
where it was created.
In the code below, I can console.log the value of an indexed array (**** works perfectly here ****
) when I'm inside of the then{}
, but I can't get it to work outside of the then{}
where I created it. See **** does NOT work here ****
.
Also, I can see the data when I consol.log the entire array **** I can see the data in the array though. ****
, but I can't access specific values. Screenshot below.
Any help is greatly appreciated.
My Code
var songsList = [];
//Fetch JSON from URL -> https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('data.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var songData = (JSON.stringify(myJson));
var obj = JSON.parse(songData);
// https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
for (index = 0; index < obj.length; ++index) {
var newSong = [];
var songUid = obj[index]['uid'];
var songName = obj[index]['songName'];
var songGenere = obj[index]['genere'];
var songUrl = obj[index]['url'];
var songID = songUrl.split("be/");
songID = songID[1];
var songListen = obj[index]['listen'];
var email = obj[index]['email'];
newSong.push(songUid);
newSong.push(songName);
newSong.push(songGenere);
newSong.push(songUrl);
newSong.push(songID);
newSong.push(songListen);
newSong.push(email);
songsList.push(newSong);
} //
console.log('Song Title - '+songsList[0][1]); // **** works perfectly here ****
});
console.log('Song Title - '+songsList[0][1]); // **** does NOT work here ****
console.log('Song Title - '+songsList); // **** I can see the data in the array though. ****