How to get the first key name of a JavaScript object ?
Last Updated :
10 Jan, 2025
In JavaScript, accessing the first key name of an object involves identifying the initial property defined within that object. This concept is useful when you need to interact with or manipulate object properties in a specific order, particularly when the sequence of properties is relevant.
Here we have some common approaches to get the first key name of a JavaScript object:
Using Object.keys() Method
The Object.keys() method retrieves an array of a JavaScript object's keys. To get the first key name, access the first element of this array using [0]. This approach is straightforward and commonly used to obtain the initial key in an object.
Syntax
Object.keys(obj);
Example: In this example, the Object.keys(obj)[0] retrieves the first key from the object obj. Here, it returns a.
JavaScript
const obj = { a: 1, b: 2, c: 3 }; // Object with keys
const firstKey = Object.keys(obj)[0]; // Get first key
console.log(firstKey); // "a"
Using for...in Loop
The for...in loop iterates over the enumerable properties of a JavaScript object. To get the first key name, you can use this loop and break immediately after the first iteration, capturing the first key. This approach is simple and direct for accessing the initial key.
Syntax
for (let i in obj1) {
// Prints all the keys in
// obj1 on the console
console.log(i);
}
Example: In this example we use a for...in loop to capture the first key of inputObject. It logs "1" after exiting the loop immediately upon finding the first key.
JavaScript
const inputObject = { 1: 'JavaScript', 2: 'Python', 3: 'HTML' };
console.log("The first key name of the object is: ");
let firstKey;
for (let key in inputObject) {
firstKey = key; // Capture the first key
break; // Exit loop after the first key
}
console.log(firstKey); // Output: "1"
OutputThe first key name of the object is:
1
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.