How to access the first property of a Javascript object?

The Question :

664 people think this question is useful

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

The Question Comments :
  • it’s probably better to transform it into an Array first

The Answer 1

1484 people think this answer is useful
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.

The Answer 2

127 people think this answer is useful

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

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

The Answer 3

84 people think this answer is useful

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

The Answer 4

47 people think this answer is useful

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.

The Answer 5

25 people think this answer is useful

A one-rule version:

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

The Answer 6

24 people think this answer is useful

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

The Answer 7

11 people think this answer is useful

Solution with lodash library:

_.find(example) // => {name: "foo1"}

but there is no guarantee of the object properties internal storage order because it depends on javascript VM implementation.

The Answer 8

10 people think this answer is useful

The top answer could generate the whole array and then capture from the list. Here is an another effective shortcut

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

The Answer 9

8 people think this answer is useful

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.

The Answer 10

3 people think this answer is useful

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.

The Answer 11

3 people think this answer is useful

I don’t recommend you to use Object.keys since its not supported in old IE versions. But if you really need that, you could use the code above to guarantee the back compatibility:

if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
    hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
    dontEnums = [
      'toString',
      'toLocaleString',
      'valueOf',
      'hasOwnProperty',
      'isPrototypeOf',
      'propertyIsEnumerable',
      'constructor'
    ],
    dontEnumsLength = dontEnums.length;

return function (obj) {
  if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');

  var result = [];

  for (var prop in obj) {
    if (hasOwnProperty.call(obj, prop)) result.push(prop);
  }

  if (hasDontEnumBug) {
    for (var i=0; i < dontEnumsLength; i++) {
      if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
    }
  }
  return result;
}})()};

Feature Firefox (Gecko)4 (2.0) Chrome 5 Internet Explorer 9 Opera 12 Safari 5

More info: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys

But if you only need the first one, we could arrange a shorter solution like:

var data = {"key1":"123","key2":"456"};
var first = {};
for(key in data){
    if(data.hasOwnProperty(key)){
        first.key = key;
        first.content =  data[key];
        break;
    }
}
console.log(first); // {key:"key",content:"123"}

The Answer 12

3 people think this answer is useful

To get the first key name in the object you can use:

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

Returns a string, so you cant access nested objects if there were, like:

var obj = { first: { someVal : { id : 1} }; Here with that solution you can’t access id.

The best solution if you want to get the actual object is using lodash like:

obj[_.first(_.keys(obj))].id

To return the value of the first key, (if you don’t know exactly the first key name):

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

if you know the key name just use:

obj.first

or

obj['first']

The Answer 13

2 people think this answer is useful

Here is a cleaner way of getting the first key:

var object = {
    foo1: 'value of the first property "foo1"',
    foo2: { /* stuff2 */},
    foo3: { /* stuff3 */}
};

let [firstKey] = Object.keys(object)

console.log(firstKey)
console.log(object[firstKey])

The Answer 14

1 people think this answer is useful

if someone prefers array destructuring

const [firstKey] = Object.keys(object);

The Answer 15

0 people think this answer is useful

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.

The Answer 16

0 people think this answer is useful

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;

The Answer 17

0 people think this answer is useful

Any reason not to do this?

> example.map(x => x.name);

(3) ["foo1", "foo2", "foo3"]

The Answer 18

0 people think this answer is useful

You can use Object.prototype.keys which returns all the keys of an object in the same order. So if you want the first object just get that array and use the first element as desired key.

const o = { "key1": "value1", "key2": "value2"};
const idx = 0; // add the index for which you want value
var key = Object.keys(o)[idx];
value = o[key]
console.log(key,value); // key2 value2

The Answer 19

0 people think this answer is useful

we can also do with this approch.

var example = {
  foo1: { /* stuff1 */},
  foo2: { /* stuff2 */},
  foo3: { /* stuff3 */}
}; 
Object.entries(example)[0][1];

Add a Comment