1

I am creating an array of objects, I need to access the properties in this array of objects and yet, when I try to do this I get get an error of 'undefined'. I've searched for this problem but I can't find anything that I've done that would prevent it from working.

To start I define and empty array.

var gantt_data_array = [];

I then access my data using ajax from a controller. On success, I iterate over the results and push the required object into the array.

var get_data = $.ajax({    
    url: "/Gantt/Read_Gantt",    
    success: function (result) {
        $.each(result, function (d, v) {   
            gantt_data_array.push({
                "startDate": v.Commencement_Date,
                "endDate": v.End_Date,
                "taskName": v.Vessel_Name,
                "status": v.Firm_Status
            });
        })
    },
    error: function (xhr, status, error) {
        console.log("error")
    }
});

I then try to access a property for use in other places in the following manner, which returns as undefined:

console.log(gantt_data_array['startDate'])

I checked the array for data by logging out the array itself

console.log(gantt_data_array)

Which shows the data in the expected format

[]
    0: { startDate: ...something, endDate: ...something, taskName: ...something, status: ...something }
    1: { startDate: ...something, endDate: ...something, taskName: ...something, status: ...something }

When I log the length of the array however console.log(gantt_data_array.length) it returns 0. Am I pushing this correctly? Have I made a simple mistake? I can't see what would be causing this problem.

Yanayaya
  • 2,044
  • 5
  • 30
  • 67
  • You've done a great job describing the problem (and using text rather than pictures of text, like so many others do)!! What's happening is a combination of [this](https://stackoverflow.com/questions/23667086/) and [this](https://stackoverflow.com/questions/38660832/). You're logging your array before the ajax success function runs, while the array is still empty, which is why the summary text in the console is just `[]` (empty array). Later, the ajax success function runs, adding entries to the array. Then you're clicking the arrow to expand the array in the console. ... – T.J. Crowder Nov 01 '21 at 11:11
  • ... At that point, it has entries in it, so the console is showing them to you. The expanded bit shows you what the array has in it *when you expanded it*, not when it was logged. – T.J. Crowder Nov 01 '21 at 11:11

0 Answers0