How to Get the First Key Name of a JavaScript Object

In this tutorial, we will discuss the two mathods of getting the first key of a JavaScript Object.

Object.keys

Since objects do not have index referencing, you can't complete your task by just calling for the first element or last element.

For that purpose, you should use the object.keys method to get access to all the keys of object.

Then you can use indexing like Object.keys(objectName)[0] to get the key of first element:

Javascript Object.keys method
let obj = { valueName: 'someVal' }; let val = obj[Object.keys(obj)[0]]; //returns 'someVal' console.log(val);

The for...in Loop

The second method is for...in loop. Try it and break after the first iteration so as to get the first key of the object:

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

Example:

Javascript for..in loop and break after the first iteration
let obj = { first: 'firstVal', second: 'secondVal' }; for (let prop in obj) { console.log(prop); break; }

Object.keys() and for...in

Object.keys() is used to return enumerable properties of a simple array, of an array like an object, and an array like object with random ordering.

Object.keys() returns the array whose elements are strings corresponding to the enumerable properties found upon the object. The property order is similar to that given by the object manually in a loop applied to the properties.

The for...in loop iterates over "enumerable" properties of the object and applies to all objects that have these properties. An enumerable property is the property of an object that has an Enumerable value of true.