2

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?

1
  • i don't think you can use $scope.data.length, as its not an array..! Commented Feb 6, 2015 at 3:04

3 Answers 3

3

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'];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

If you just need to get the number of keys in your object then try use.

Object.keys(obj).length

Comments

1

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'];
            }
        }
    }
};

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.