Trouble getting size of an array in a js object inside controller
-
21-12-2019 - |
Question
I want to get the size of some data I am retrieving in my controller - I have tried the following code; both utilizing a new Object.size
function and attempted to get the length
property directly through .length
$scope.book = DataService.getBooks();
console.log($scope.book);
-- this function was only added to try and solve the problem.
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
console.log(Object.size($scope.book['value']))
console.log($scope.book['value'].length)
Here is a picture of what is stored in the variable. As you can see the .value
is clearly an array containing 3 objects and a length
property - why can I not directly retrieve this?
Edit: Calling console.log($scope.book['value'].length)
gives me this type error:
TypeError: Cannot read property 'length' of undefined
Solution
Since $scope.book is a promise, it is likely unresolved on your console.log and give you the type error.
So something like this should solve your problem
$scope.book.$promise.then(function(){
console.log($scope.book['value'].length);
});
The size function is unnecessary and confusing since you are setting it on Object, but trying to get the length of an array.