Course

JavaScript Object.keys() method: Syntax, Usage, and Examples

The Object.keys() method in JavaScript returns an array of a given object’s own enumerable property names. It’s a useful tool for iterating over keys, checking what data an object holds, or transforming objects into arrays. With the JavaScript Object.keys() method, you can write clean and efficient code when working with objects dynamically.

Whether you’re accessing API responses, looping through form values, or transforming configurations, knowing how to use Object.keys() JavaScript techniques helps you get the most out of object data structures.

How to Use JavaScript Object.keys

Here’s the basic syntax:

jsx
Object.keys(obj)
  • obj: The object whose enumerable properties you want to list.
  • Returns: An array of string keys from the object.

Basic Example

jsx
const user = { name: "Alice", age: 30, role: "admin" }; const keys = Object.keys(user); console.log(keys); // ["name", "age", "role"]

This method extracts the object’s property names into an array.

When to Use object.keys JavaScript

Iterate Over Object Properties

You can loop over an object’s keys and access each value:

jsx
const car = { brand: "Toyota", model: "Camry", year: 2023 }; Object.keys(car).forEach((key) => { console.log(`${key}: ${car[key]}`); });

This is ideal when working with dynamic or unknown objects.

Convert an Object to an Array

Need to display or process object data as an array?

jsx
const product = { id: 101, name: "Book", price: 19.99 }; const keyList = Object.keys(product); // ["id", "name", "price"]

Perfect for form validation, dynamic tables, or JSON processing.

Count Object Properties

jsx
const settings = { theme: "dark", notifications: true, autoSave: false }; const count = Object.keys(settings).length; console.log("Settings count:", count); // 3

The length of the returned array gives you the number of keys.

Examples of JavaScript object.keys in Practice

Get Object Keys from Nested Objects

jsx
const data = { user: { name: "Eli", email: "eli@example.com" }, status: "active" }; const outerKeys = Object.keys(data); const innerKeys = Object.keys(data.user); console.log(outerKeys); // ["user", "status"] console.log(innerKeys); // ["name", "email"]

You can use Object.keys() on any level of an object.

Handle Arrays as Objects

Arrays are also technically objects, so this works:

jsx
const items = ["apple", "banana", "cherry"]; console.log(Object.keys(items)); // ["0", "1", "2"]

This helps when working with sparse arrays or custom indexes.

Combine with map()

jsx
const person = { firstName: "Jane", lastName: "Doe" }; const upperKeys = Object.keys(person).map((key) => key.toUpperCase()); console.log(upperKeys); // ["FIRSTNAME", "LASTNAME"]

Great for transforming or displaying keys in a new format.

Filter Object Keys Dynamically

jsx
const profile = { username: "dev123", password: "secret", email: "dev@example.com" }; const publicKeys = Object.keys(profile).filter((key) => key !== "password"); console.log(publicKeys); // ["username", "email"]

This pattern is handy when you need to hide sensitive data.

Learn More About JavaScript Object.keys

Difference Between Object.keys, Object.values, and Object.entries

  • Object.keys(obj): returns keys.
  • Object.values(obj): returns values.
  • Object.entries(obj): returns [key, value] pairs.
jsx
const user = { name: "Liam", age: 28 }; console.log(Object.keys(user)); // ["name", "age"] console.log(Object.values(user)); // ["Liam", 28] console.log(Object.entries(user)); // [["name", "Liam"], ["age", 28]]

Choose the one that fits your task best.

Use with Destructuring

jsx
const info = { name: "Emma", country: "Canada" }; const [firstKey] = Object.keys(info); console.log(firstKey); // "name"

You can quickly extract specific keys using array destructuring.

Deleting Keys After Getting Them

Combine Object.keys() with delete to remove specific keys:

jsx
const user = { id: 1, token: "abc123", name: "Sara" }; Object.keys(user).forEach((key) => { if (key === "token") { delete user[key]; } }); console.log(user); // { id: 1, name: "Sara" }

This lets you control exactly what stays or goes in your object.

Create Key-Only Lists

For dropdowns or dynamic UI, Object.keys() helps generate key-based lists:

jsx
const options = { optionA: true, optionB: false, optionC: true }; const choices = Object.keys(options).filter((key) => options[key]); console.log(choices); // ["optionA", "optionC"]

This logic is often used in form generators or UI logic.

JavaScript Get Object Keys Without Inherited Properties

Object.keys() only returns own enumerable properties—not inherited ones. So if you extend an object from a prototype, it won’t include inherited keys:

jsx
function Animal() { this.legs = 4; } Animal.prototype.sound = "growl"; const dog = new Animal(); console.log(Object.keys(dog)); // ["legs"]

If you want all properties, including non-enumerable or inherited ones, consider for...in, Object.getOwnPropertyNames(), or Reflect.ownKeys().

Object.keys and Performance

Object.keys() is fast and optimized in modern engines. However, if you’re dealing with very large objects and performance matters, avoid calling it repeatedly inside loops. Cache the result:

jsx
const keys = Object.keys(bigObject); for (let i = 0; i < keys.length; i++) { const key = keys[i]; doSomething(bigObject[key]); }

This avoids recalculating the key list multiple times.

The JavaScript object.keys method gives you an easy and efficient way to work with an object’s property names. Whether you’re iterating through data, creating summaries, or transforming structures, object.keys JavaScript techniques help you understand and manipulate your objects with precision.