You can use different built-in methods to get a list of keys from a JavaScript object. There are many ways to extract keys from the object. Let’s explore some of the ways by which this can be done.
Using Object.keys()
The most common method to do this is by using Object.keys()
let obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
}
let keys = Object.keys(obj);
console.log(keys);
Output
["key1","key2","key3"]
Using for..in loop
In this approach, we can use for…in the loop to iterate through the object and get the keys.
let obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
}
for (let key in obj) {
console.log(key);
}
output
"key1"
"Key2"
"Key3"
Using Object.getOwnPropertyNames()
This method returns an array of all property names (including non-enumerable but excluding symbols).
let obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
}
const keys = Object.getOwnPropertyNames(obj);
console.log(keys);
Output
["key1","key2","key3"]
Similar Reads
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays