How to access the first property of a Javascript object?

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

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

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


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.


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

Object.values(obj)[0]; // returns 'someVal'

Using this you can access also other properties by indexes. Be aware tho! Object.keys or Object.values 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.