JavaScript – Get Object Key List

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