How to get object keys from JavaScript object ?

📋 Table Of Content
In this short tutorial, we will learn how to extract the keys from JavaScript objects.
To get only the keys from an object we can use,
- Object.keys(), and
- for...in loop
Let's check each with examples.
Get object keys using Object.keys() method
The Object.keys() method takes an object and returns an array of strings of the object's keys.
Syntax:
Object.keys(obj)
Example:
const car = {
color: 'red',
wheel: 4,
fuel: 'diesel',
number: 798765
}
const keys = Object.keys(car)
console.log(keys)
Output:
[ 'color', 'wheel', 'fuel', 'number' ]
Getting JavaScript object key list using for...in loop
Another way to extract a key is to loop through each object property and extract the keys from it.
The for..in loop iterates all the property keys of an object in JavaScript. While iterating through the property, a key
is assigned to each key variable of the object.
Syntax:
for (const key in object) {
// code here
}
Example:
const car = {
color: 'red',
wheel: 4,
fuel: 'diesel',
number: 798765
}
for (const key in car){
console.log(key)
}
Output:
color
wheel
fuel
number
So following this you can get the list of keys of any object.
Related Topics: