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.
4 Answers 4
If I understand your question, it's the simplest ever thing.
for(var k in obj){
console.log(k);
}
4 Comments
Alternatively:
Object.keys(obj).forEach(function(key) { console.log(key); });
Comments
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])
}
1 Comment
Are you trying to print out the keys and values?
for(var k in obj){
console.log(k,obj[k]);
}
obj.lengthis undefined becauseobj, as you've defined it, is a object and not an array.