thousight thousight - 5 months ago 17
Javascript Question

Javascript object becomes undefined in a for loop

When I am trying to add the usersData object to the filter idToName inside the for loop, it suddenly becomes undefined. Shouldn't the usersData get the value before the for loop runs? How should I fix it?

Project.getProjects()
.success(function(data) {
vm.projects = data;
var projectLength = vm.projects.length;

// Get usersData
User.allUsers()
.success(function(data) {
usersData = data;
console.log(usersData); // It prints the object
})

for (var i = 0; i < projectLength; i++){
console.log(usersData); // It prints undefined
vm.projects[i].assigneeID = $filter('idToName')(vm.projects[i].assigneeID, usersData);
}
})

Answer

It must be due to async calls. Try updating your code to following

// Get usersData
    User.allUsers()
    .success(function(data) {
      usersData = data;
      console.log(usersData); // It prints the object
      for (var i = 0; i < projectLength; i++){
          console.log(usersData); // It prints undefined
           vm.projects[i].assigneeID = $filter('idToName')(vm.projects[i].assigneeID, usersData);
      } 
    })