JS: Access outside variable inside anonymous function

65 views Asked by At

I am GETing JSON from a web server, with the intention to save the JSON string later. But the JSON is an array of objects, and the objects contain a lot of properties I do not need, so I clean them up using js. Each of the objects then look like this.

{
    "property1":"value1",
    "property2":"value2",
    "idOfExternalResource":"resourceid"
}

These objects don't have all of the properties I need, and I have to make another server call to get the values of the properties I do need using idOfExternalResource, like so:

for(var k = 0; k < jsonObjects.length; ++k) {
if (..jsonObjects[k] contains a defined idOfExternalResource..)
{
    var resURL = "/someurl/"+jsonObjects[k].idOfExternalResource;
    var request = new XMLHttpRequest();
    request.open("GET", resUrl, true);
    request.send();

    request.onreadystatechange = function() {
        if (orgRequest.readyState == 4 /*and other checks*/)
        {
            console.log(request.responseText) //logs what it's supposed to
            var externalResObject = JSON.parse(request.responseText); //parses the object fine
            jsonObjects[k].neededProperty = orgNameObject.value; //causes error       
        }
    }
}
}

Which gives me this error: TypeError: Result of expression 'jsonObjects[k]' [undefined] is not an object.

I assume it does this because I can't access jsonObjects[k] from inside the anonymous function. Is there any way to work around/fix this?

0

There are 0 answers