- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Tile
- Type conversion
- While loop
JAVASCRIPT
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:
Object.keys(obj)
obj
: The object whose enumerable properties you want to list.- Returns: An array of string keys from the object.
Basic Example
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:
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?
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
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
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:
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()
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
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.
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
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:
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:
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:
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:
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.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.