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
BellamyGray
451 gold badge1 silver badge3 bronze badges
1 Answer 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
nb1987
1,4201 gold badge12 silver badges13 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
BellamyGray
I figured it had something to do with the loop. Thanks!
nb1987
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.
lang-js
returnkeyword from theforloop.