Learn how to get the keys of an object in JavaScript using the Object.keys()
method. This method returns an array of the keys of the object, which you can use to access and manipulate the object’s properties.
Object.keys(obj)
The Object.keys()
method returns an array of the keys of the object.
Get object key name JavaScript example
Simple example code.
const myObject = {
name: 'John',
age: 30,
city: 'New York'
};
const keys = Object.keys(myObject);
console.log(keys);
Output:
JavaScript gets the object key name
To get the name of a key in a JavaScript object, you can simply access it using the dot notation or square bracket notation.
const myObject = {
name: 'John',
age: 30,
city: 'New York'
};
console.log(myObject.name); // 'John'
console.log(myObject['age']); // 30
If you want to get the name of a key dynamically, you can use the Object.keys()
method to get an array of the keys of the object, and then iterate over the array to access the name of each key. Here’s an example:
const myObject = {
name: 'John',
age: 30,
city: 'New York'
};
const keys = Object.keys(myObject);
keys.forEach(key => {
console.log(key); // 'name', 'age', 'city'
});
How to get the first key name of a JavaScript object
In JavaScript, you can get the first key name of an object in a couple of ways. One common approach is to use the Object.keys()
method to extract an array of all the keys in the object and then retrieve the first element of that array.
const myObject = {
name: 'John',
age: 30,
occupation: 'Developer'
};
const firstKey = Object.keys(myObject)[0];
console.log(firstKey);
Output: “name”
Another approach to getting the first key name of an object is by using a for...in
loop.
const myObject = {
name: 'John',
age: 30,
occupation: 'Developer'
};
let firstKey;
for (const key in myObject) {
firstKey = key;
break;
}
console.log(firstKey); // Output: "name"
Comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version