BellamyGray
BellamyGray

Reputation: 45

Object Keys to Array

The challenge asks us to create an array from a given object's keys (without using Objects.keys).

Here is my code:

 function getAllKeys(object){ 
   var array = []; 
   for(var key in object){
   array.push(key);
   return array;     
    } 
      } 

  var myObj={   
  name:"bellamy",  
  age:25 }; 

  getAllKeys(myObj);

For some reason it's only returning the first key

[ 'name' ]

Any help would be much appreciated! I'm sure it's a simple fix, just one I'm not aware of as an extreme novice.

Upvotes: 0

Views: 174

Answers (1)

nb1987
nb1987

Reputation: 1410

You need to move your return outside of your loop:

function getAllKeys(object){ 
   var array = []; 
   for(var key in object){
       array.push(key);
   } 
   return array;   
 } 

 var myObj = {   
    name:"bellamy",  
    age:25 
 }; 

 getAllKeys(myObj);

This is because your function will immediately return when it first encounters return, which in your example is in the first iteration of the loop.

Upvotes: 1

Related Questions