0

I have a problem with a for/in inside a function that does not work.

$scope.files = [];

jobslisting.getJobs(function(data){

     for(var i = 0; i < data.length; i++){
         $scope.files.push({name:data[i]});
     }

     console.log(data);        
     console.log($scope.files);

});

console.log(data) returns:

Object {2: "item1", 3: "item2", 4: "item3", 5: "item4", 6: "item5", 7: "item6", 8: "item7", 9: "item8"}

console.log($scope.files) returns

[]

Thanks in advance for any advices!

2 Answers 2

1

The issue is that your for loop never runs, because you are calling .length on an object and not on an array.

Instead, replace your for loop with angular.forEach(), like this:

angular.forEach(data, function(val, key) {
    $scope.files.push({name: val});
});

More info: https://docs.angularjs.org/api/ng/function/angular.forEach

Sign up to request clarification or add additional context in comments.

Comments

1

It looks like data is not an Array, but an object with numbers as the keys. I would check to make absolutely sure wherever you call the service from is sending in an Array. It might also be wise to use an iterator method for data, so it will work with arrays or objects. For that you can roll your own method, or use one that is built into underscore or lodash.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.