How to Get JavaScript Object's First Own Enumerable Key Name?

To get an object's first key/property name from its own (i.e. non-inherited) enumerable properties, you can do either of the following:

// ES5+
Object.keys(obj)[0];
// ES8+
const [key] = Object.entries(obj)[0];

You should note that, prior to ES2020/ES11, the order of the keys is not guaranteed when using either of these methods. If you really need to rely on the order of the object then you should consider using Map (which uses insertion order) or sort the resulting array.

Starting from ES2020/ES11, the order of Object.keys() and Object.entries() is the same as that of a for...in loop. This means when using either of these methods, the order of the object (own, enumerable) properties would be the following:

  1. Numeric keys in ascending order;
  2. String keys in insertion order;
  3. Symbols in insertion order.

For example:

const obj = { foo: 'bar', 123: 'baz', 0: 'qux' };
const firstKey = Object.keys(obj)[0];

console.log(firstKey); // '0'
const obj = { foo: 'bar', 123: 'baz', 0: 'qux' };
const [firstKey] = Object.entries(obj)[0];

console.log(firstKey); // '0'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.