Is there an elegant way to access the first property of an object...
- where you don't know the name of your properties
- without using a loop like
for .. in
or jQuery's$.each
For example, I need to access foo1
object without knowing the name of foo1:
var example = {
foo1: { /* stuff1 */},
foo2: { /* stuff2 */},
foo3: { /* stuff3 */}
};
Using this you can access also other properties by indexes. Be aware tho!
Object.keys
return order is not guaranteed as per ECMAScript however unofficially it is by all major browsers implementations, please read https://stackoverflow.com/a/23202095 for details on this.A one-rule version:
If you need to access "the first property of an object", it might mean that there is something wrong with your logic. The order of an object's properties should not matter.
This has been covered here before.
The concept of first does not apply to object properties, and the order of a for...in loop is not guaranteed by the specs, however in practice it is reliably FIFO except critically for chrome (bug report). Make your decisions accordingly.
Use
Object.keys
to get an array of the properties on an object. Example:Documentation and cross-browser shim provided here. An example of its use can be found in another one of my answers here.
Edit: for clarity, I just want to echo what was correctly stated in other answers: the key order in javascript objects is undefined.
Try the
for … in
loop and break after the first iteration: