Reputation: 583
I have this $scope.data object:
$scope.data = {
'8':{
'id':'81',
'name':'anna',
},
'9':{
'id':'82',
'name':'sally',
},
};
I am getting the id by using for loop in this way.
$scope.getID = function(id){
for(var i=0;i<$scope.data.length;i++){
if(id == $scope.data[i].id)
return $scope.data[i].name;
}
}
};
But it doesn't work at all. I am wondering why? Is it I call the id at the right way?
Upvotes: 2
Views: 10975
Reputation: 4212
It might helps you -
$scope.users=data;
$scope.getUserNameBYID = function(id){
if(users !== undefined && users.length >0){
for(key in users) {
var obj = users[key];
if( obj['id'] === id ) {
return obj['name'];
}
}
}
};
Upvotes: 1
Reputation: 331
If you just need to get the number of keys in your object then try use.
Object.keys(obj).length
Upvotes: 2
Reputation: 100205
as its not an array of objects you can't use $scope.data.length
, try using for…in
loop, as:
for(key in $scope.data) {
var obj = $scope.data[key];
if( obj['id'] == id ) {
return obj['name'];
}
}
Upvotes: 3