HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to access the first property of a Javascript object?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
propertyobjecthowaccessthejavascriptfirst

Problem

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

Solution

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.

Code Snippets

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

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

Context

Stack Overflow Q#983267, score: 1953

Revisions (0)

No revisions yet.