-1

I am curious but Google is not helping on this one...

We are looking for a tidy way of using an object key (it is an object containing functions) while also having clean access to the key names.

var obj={'key1':'val1','key2':'val2','key3':'val3'};

To get the desired key names in a loop we do: EDIT: this is wrong!

for(var i=0;i<obj.length;i++){
 console.log(Object.keys(obj)[i]);
 }

but would it be possible in this kind of loop?

for(var k in obj){
 //?
 }

I have seen combination loops before using &&. Is JavaScript able to do an elegant combination of both?

The closest I have got without disrupting the standard loop is:

var i=0;
for(var k in obj){
 console.log(Object.keys(obj)[i]);
 i++;
 }

but it is hardly elegant, not very innovative, it is more of a work around because 'i' is declared outside of the loop. Everything else we have tried errors.

asked Jul 17, 2014 at 13:06
3
  • 1
    Your first loop isn't even valid. obj.length is undefined because obj, as you've defined it, is a object and not an array. Commented Jul 17, 2014 at 13:09
  • thanks, I think my brain is frazzled Commented Jul 17, 2014 at 13:13
  • @8DK This happens. Don't worry, just go on... Commented Jul 17, 2014 at 13:14

4 Answers 4

5

If I understand your question, it's the simplest ever thing.

for(var k in obj){
 console.log(k);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Why the downvote ? Wasn't it what's asked ?
(I don't mean it should be upvoted either...)
Well it is a perfectly good answer.
I know! some people are haters on here! Lol i must be REALLY tired. that is soooo easy its shocking! +1
1

Alternatively:

Object.keys(obj).forEach(function(key) { console.log(key); });
answered Jul 17, 2014 at 13:10

Comments

1

If you need the keys:

for(var k in obj) {
 console.log(k)
}

If you need the values:

for(var k in obj) {
 console.log(obj[k])
}
answered Jul 17, 2014 at 13:10

1 Comment

+1, I like the style of your answer
0

Are you trying to print out the keys and values?

for(var k in obj){
 console.log(k,obj[k]);
}
answered Jul 17, 2014 at 13:10

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.