How to access the first property of an object in Javascript?

How to access the first property of an object in Javascript?

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 */}
};

Solutions/Answers:

Solution 1:

var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'

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.

Solution 2:

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

for (var prop in object) {
    // object[prop]
    break;
}

Solution 3:

Use Object.keys to get an array of the properties on an object. Example:

var example = {
    foo1: { /* stuff1 */},
    foo2: { /* stuff2 */},
    foo3: { /* stuff3 */}
};

var keys = Object.keys(example); // => ["foo1", "foo2", "foo3"] (Note: the order here is not reliable)

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.

Solution 4:

You can also do Object.values(example)[0].

Solution 5:

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).

Solution 6:

A one-rule version:

var val = example[function() { for (var k in example) return k }()];