-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.

8DK
  • 704
  • 1
  • 5
  • 15

4 Answers4

5

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

for(var k in obj){
    console.log(k);
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Alternatively:

Object.keys(obj).forEach(function(key) { console.log(key); });
Pointy
  • 405,095
  • 59
  • 585
  • 614
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])
}
William Barbosa
  • 4,936
  • 2
  • 19
  • 37
0

Are you trying to print out the keys and values?

for(var k in obj){
    console.log(k,obj[k]);
}
Naren
  • 1,910
  • 1
  • 17
  • 22