I'm facing an issue while trying to fetch data from a CSV file and store it in an array of objects. Although I understand that global variables are generally discouraged, I'm struggling to find a better way to handle the data and access it across multiple functions.
Here's the snippet of code I have:
let myData = new Array;
$(document).ready( function () {
$.get('./datafile.csv', function(data) {
let rows = data.split("\n");
for(let i = 1; i < rows.length; i++){
let line = rows[i].split(",");
let obj = {
index: i,
img: line[0],
caption: line[1],
desc: line[2]
};
myData.push(obj);
}
console.log(myData); //1
});
console.log(myData); //2
//My goal is to target specific elements on the page and assign attributes based on the objects in my data array, but everything returns as undefined
});
The first console log correctly displays my data, however, at the second instance, it shows an empty array. I came across this article discussing global variables in JavaScript, which has left me puzzled about what might be going wrong.