If I have a JS object like:
var foo = { 'bar' : 'baz' }
If I know that foo
has that basic key/value structure, but don't know the name of the key, what's the easiest way to get it? for ... in
? $.each()
? I hope there's something better....
If I have a JS object like:
var foo = { 'bar' : 'baz' }
If I know that foo
has that basic key/value structure, but don't know the name of the key, what's the easiest way to get it? for ... in
? $.each()
? I hope there's something better....
Since you mentioned
$.each()
, here's a handy approach that would work in jQuery 1.6+:Well
$.each
is a library construct, whereasfor ... in
is native js, which should be betterIf 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 usesfor...in
btw):Of course if you want both, key and value, then
for...in
is the only reasonable solution.I don't see anything else than
for (var key in foo)
.Given your Object:
To get
bar
, use:To get
baz
, use:Assuming a single object
A one liner for you: