0

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.

asked Mar 25, 2017 at 20:32
1
  • 1
    Remove the return keyword from the for loop. Commented Mar 25, 2017 at 20:32

1 Answer 1

1

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.

answered Mar 25, 2017 at 20:33
Sign up to request clarification or add additional context in comments.

2 Comments

I figured it had something to do with the loop. Thanks!
No problem--I am glad to help. If my answer solved your problem, please feel free to mark it as accepted by clicking on the check mark beside the answer to toggle it from gray to green.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.