0

Long story short: I have to read data from a .csv file with JavaScript and I have a function which fills my global defined array with data (= each array's entry is a new Object).

The problem is that I can access the array by its index only inside the function (console.log(requestors[0].ID);) AND I need it accessible outside the function so I can modify / use it.

What's the wrong thing I am doing?

Thanks a lot!

var requestors  = [];

class Requestor {
    constructor(ID, RequestorName, RequestorSurname, RequestorGivenname, RequestorUID, RequestorEmail, Location, Department) {
        this.ID = ID;
        this.RequestorName = RequestorName;
        this.RequestorSurname = RequestorSurname;
        this.RequestorGivenname = RequestorGivenname;
        this.RequestorUID = RequestorUID;
        this.RequestorEmail = RequestorEmail;
        this.Location = Location;
        this.Department = Department;
    }
}

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "./app/csv/requestors.csv",
        dataType: "text",
        success: function(data) {
            processRequestors(data);
        }
     });
});

var h = 0;
function processRequestors(allRequestorsEntries) {
    var allRequestorsRows = allRequestorsEntries.split(/\r\n|\n/);
    var headers = allRequestorsRows[0].split(',');

    for (var i = 1; i < allRequestorsRows.length; i ++) {
        var data = allRequestorsRows[i].split(',');
        if (data.length === headers.length) {
            requestors[h] = new Requestor();
            for (var j = 0; j < headers.length; j ++) {
                requestors[h][headers[j]] = data[j];
            }
            h ++;
        }
    }

    console.log(requestors[0].RequestorName); // value
}

console.log(requestors[0].RequestorName); // undefined
Alex
  • 125
  • 2
  • 9

0 Answers0