0

I have an array modelProps which is a parsed JSON object. modelProps is assigned a value in my getModelProps() function which looks like this:

function getModelProps() {
    console.log("GET MODEL PROPERTIES")
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (this.readyState==4 && this.status==200) {
            var myObj = JSON.parse(this.responseText);
            myObj.forEach(function (record) {
                modelProps.push(record)
            })
        }
    }

    xmlhttp.open("GET","./php/getModelProps.php",true);
    xmlhttp.send();
}

After calling the function, when I simply log modelProps, I get the output:

output after console.log(modelProps)

This confirms that modelProps isn't empty. But the problem becomes apparent when I try to access it by other means. Firstly, assuming that modelProps was just an array, I tried doing console.log(modelProps[0]) which gave an output of undefined. Afterwards, I logged the typeof modelProps to find out that it was an Object. After finding this out, I tried logging the entries(), keys() and values(), only to get empty arrays returned.

Can someone please explain why this is? Any help would be appreciated.

EternalHour
  • 7,327
  • 6
  • 31
  • 54
  • We need more context around this variable. Such as if you are retrieving it via ajax, and at what point in time you are trying to access it. – Taplar Jan 19 '21 at 18:50
  • @Taplar my bad, I'll re-edit the post to add more context. – shoaib-jpeg Jan 19 '21 at 18:51
  • Hi, did you mean that you did this: console.log(modelProp[0]) as modelProp isn't defined as far as I can see so it would be undefined in the console. – A Haworth Jan 19 '21 at 19:02
  • @AHaworth that was just a typo by me in the question. In my code I had it as modelProps, not modelProp – shoaib-jpeg Jan 19 '21 at 19:08
  • @shoaib-jpeg I think you'll need to show the code for how you're trying to log the object or access it by other means. It might be, as Jared Smith suggested, a timing/asynchronous issue – Codebling Jan 19 '21 at 19:14

0 Answers0