musikele
musikele

Reputation: 363

iterating over a map, I don't get keys but numbers

I have this piece of code in Javascript / Angular :

 $scope.validCredentials = {            
        '[email protected]': 'aaa',
        '[email protected]' : 'bbb'
    };

I access the variable in this loop:

for ( var k in Object.keys($scope.validCredentials) ) {
                $log.info("K: " +  k);
}

I have read in another question here on StackOverflow that Object.keys would return me the keys of a map, and this is happening somehow, because Firebug during debug correctly gives me the two email addresses.

However the "$log" function gives me 0 (or 1, depending on the cycle), and 0 is also the value that is used later in code, when I check this value against another variable.

Any idea why? What's happening?

I have tested it on firefox and chrome, firebug or developer tools give me the emails list during debug, but the logger logs numbers.

Upvotes: 0

Views: 57

Answers (3)

Andrew Johnston
Andrew Johnston

Reputation: 1129

The loop fails because Object.keys() returns an array. See this MDN doc.

You can iterate the array using a standard For Loop

var keys = Object.keys($scope.validCredentials);
var k;

$log.debug(keys);

for (var i = 0; i < keys.length; i++) {
  k = keys[i];

  $log.info("K: " +  k);
  //K: [email protected]
  //K: [email protected]
}

Upvotes: 0

Sebastian Piu
Sebastian Piu

Reputation: 8008

This is not related to angular, when you use for you are already iterating on the keys so just remove the Object.keys call

var validCredentials = {            
        '[email protected]': 'aaa',
        '[email protected]' : 'bbb'
    };


for ( var k in validCredentials)  {
                console.debug("K: " +  k);
}

this outputs:

K: [email protected] 
K: [email protected] 

Upvotes: 1

Dylan
Dylan

Reputation: 4773

You don't need to iterate. And you're missing a '

var validCredentials = { '[email protected]': 'aaa', '[email protected]' : 'bbb'};

console.log( Object.keys(validCredentials));

Upvotes: 0

Related Questions