tags:

views:

100

answers:

6

Is there an elegant way to access the first property of an object...

  1. where you don't know the name of your properties
  2. 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 */}
};
+1  A: 

Try the for … in loop and break after the first iteration:

for (var prop in object) {
    // object[prop]
    break;
}
Gumbo
I think this is about the only option. I'm not sure you're guaranteed that the properties will be iterated in a predictable/useful order though. I.e., you may intend foo1 but get foo3. If the properties are numbered as in the example, you could do a string compare to ascertain the identifier ending in '1'. Then again, if ordinality is the main concern of the collection, you should probably use an array instead of an object.
steamer25
+2  A: 

No. An object literal, as defined by MDC is:

a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

Therefore an object literal is not an array, and you can only access the properties using their explicit name or a for loop using the in keyword.

Perspx
+1  A: 

There isn't a "first" property. Object keys are unordered.

If you loop over them with for (var foo in bar) you will get them in some order, but it may change in future (especially if you add or remove other keys).

David Dorward
+1  A: 

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.

Flavius Stef
You're right. I don't need the first one, per se, but just one of the foo properties so I can work with it. I only need one and wasn't sure if there was a way just to grab the "first" one without using for ... in.
atogle
A: 

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.

annakata
A: 

Use an array instead of an object (square brackets).

var example = [ {/* stuff1 */}, { /* stuff2 */}, { /* stuff3 */}];
var fist = example[0];

Note that you lose the 'foo' identifiers. But you could add a name property to the contained objects:

var example = [ 
  {name: 'foo1', /* stuff1 */},
  {name: 'foo2', /* stuff2 */},
  {name: 'foo3', /* stuff3 */}
];
var whatWasFirst = example[0].name;
steamer25