best way to get the key of a key/value javascript object
You can access each key individually without iterating as in:
var obj = { first: 'someVal', second: 'otherVal' };
alert(Object.keys(obj)[0]); // returns first
alert(Object.keys(obj)[1]); // returns second
You would iterate inside the object with a for loop:
for(var i in foo){
alert(i); // alerts key
alert(foo[i]); //alerts key's value
}
Or
Object.keys(foo)
.forEach(function eachKey(key) {
alert(key); // alerts key
alert(foo[key]); // alerts value
});
If you want to get all keys, ECMAScript 5 introduced Object.keys
. This is only supported by newer browsers but the MDC documentation provides an alternative implementation (which also uses for...in
btw):
if(!Object.keys) Object.keys = function(o){
if (o !== Object(o))
throw new TypeError('Object.keys called on non-object');
var ret=[],p;
for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
return ret;
}
Of course if you want both, key and value, then for...in
is the only reasonable solution.