I have an array of objects. Somehow, one of the properties goes missing within my each loop. I have tried many different types of loops and nothing resolves this issue.
someFunction(someArrayOfObjects) {
console.log(someArrayOfObjects); // logs objects as I expect them to be
$.each(someArrayOfObjects, function(index, someObject) {
console.log(someObject); // one of the properties of someObject is 'null'
});
}
UPDATE: How the array is constructed:
// constructor
var people = [];
var Person = function (name, age, photo) {
this.name = name;
this.age = age;
this.photo = null;
};
Then use ajax to get some JSON and create the objects
success: function(data) {
people.push(new Person(data['name'], data['age'])
}
Then I iterate through each of those people and make another AJAX request to get each of their photos. The callback looks like this:
function(person, photo) {
person.photo = photo;
});
I am new to javascript and async programming so wrapping my mind around callbacks was tough. I thought I had figured it out when console.log(someArrayOfObjects)
worked as I expected. I just can't figure out why the photo property reverts when the objects are logged individually.
I also tried rewriting everything in CoffeeScript because the syntax is a bit easier for me, but unfortunately the issue remains.
Thank you.
Screenshot of console:
NEW UPDATE and final answer at last
Below is the sample code, here after all ajax calls are finished then only the buildQuiz() function would be called meaning all data is ready for further use.
OLD UPDATE
As of now(might get three times but) just try below code and let me know the log..
OLD UPDATE
So It appears there has to be something going on between first and sceond log statements.
OLD UPDATE
In your success callback of
photo
data call the function to iterate.OLD ANSWER
Below code works fine. Try it out.