Parameters
- object: The JavaScript object whose keys need to be retrieved.
Return Values
- Returns an array containing the keys (property names) of the given object.
Using Object.keys() with Complex Objects
The `Object.keys()` method in JavaScript is used to extract the keys of an object and return them as an array. This is particularly useful when you’re working with complex objects that have multiple properties. Let’s discuss this in a proper step-by-step manner:
What is `Object.keys()`?
`Object.keys()` is a built-in JavaScript method that takes an object as its argument and returns an array of the object’s keys. These keys are the property names of the object. For example, if you have an object with properties like `name`, `age`, and `city`, `Object.keys()` will give you an array like `["name", "age", "city"]`.
Why Use `Object.keys()` with Complex Objects?
Complex objects often have nested structures or multiple layers of properties. For instance, an object might contain other objects, arrays, or functions as its values. Using `Object.keys()` helps you quickly access & manipulate the top-level keys of such objects without manually iterating through them.
Example: Working with a Complex Object
Let’s say you have an object representing a user profile. This object contains details like `name`, `age`, `address`, and `hobbies`. Here’s how you can use `Object.keys()` to extract the keys:
// Define a complex object
const userProfile = {
name: "John Doe",
age: 25,
address: {
city: "New York",
zipCode: "10001"
},
hobbies: ["reading", "coding", "traveling"]
};
// Use Object.keys() to get the keys of the object
const keys = Object.keys(userProfile);
// Print the keys
console.log(keys);

You can also try this code with Online Javascript Compiler
Run Code
Output:
["name", "age", "address", "hobbies"]
In this example, `Object.keys()` returns an array of the top-level keys: `["name", "age", "address", "hobbies"]`. Notice that it doesn’t dive into the nested `address` object or the `hobbies` array. It only extracts the top-level property names.
Handling Nested Objects
If you want to extract keys from nested objects, you’ll need to combine `Object.keys()` with other methods like recursion or loops. For example, here’s how you can extract keys from the nested `address` object:
// Extract keys from the nested address object
const addressKeys = Object.keys(userProfile.address);
// Print the nested keys
console.log(addressKeys);

You can also try this code with Online Javascript Compiler
Run Code
Output:
["city", "zipCode"]
This approach allows you to work with specific parts of a complex object.
Iteration over Object Keys
Iterating over object keys is a common task in JavaScript. It allows you to access & manipulate each key-value pair in an object. This is especially useful when you need to perform operations like filtering, transforming, or logging the data. Let’s discuss this in detail:
Why Iterate over Object Keys?
When you have an object, you might want to perform actions on each of its properties. For example, you might want to:
- Print all the keys & their values.
- Check if a specific key exists.
- Modify the values of certain keys.
Iterating over object keys makes these tasks straightforward.
Using `for...in` Loop
One of the most common ways to iterate over object keys is by using a `for...in` loop. This loop goes through each key in the object, allowing you to access both the key & its corresponding value.
For example:
// Define an object
const car = {
brand: "Toyota",
model: "Corolla",
year: 2020,
color: "blue"
};
// Iterate over the object keys using for...in loop
for (let key in car) {
console.log(`${key}: ${car[key]}`);
}

You can also try this code with Online Javascript Compiler
Run Code
Output:
brand: Toyota
model: Corolla
year: 2020
color: blue
In this example, the `for...in` loop iterates over each key in the `car` object. Inside the loop, `key` represents the current key (e.g., `brand`, `model`), and `car[key]` gives the corresponding value.
Using `Object.keys()` with `forEach()`
Another way to iterate over object keys is by combining `Object.keys()` with the `forEach()` method. This approach is clean & functional.
For example:
// Define an object
const car = {
brand: "Toyota",
model: "Corolla",
year: 2020,
color: "blue"
};
// Get the keys of the object
const keys = Object.keys(car);
// Iterate over the keys using forEach()
keys.forEach(key => {
console.log(`${key}: ${car[key]}`);
});

You can also try this code with Online Javascript Compiler
Run Code
Output:
brand: Toyota
model: Corolla
year: 2020
color: blue
In this example, `Object.keys(car)` returns an array of keys (`["brand", "model", "year", "color"]`). The `forEach()` method then iterates over this array, allowing you to access each key & its value.
Practical Use Case: Filtering Object Keys
Let’s say you want to filter out specific keys from an object. For example, you might want to exclude the `year` property. Let’s see how you can do it:
// Define an object
const car = {
brand: "Toyota",
model: "Corolla",
year: 2020,
color: "blue"
};
// Filter out the 'year' key
const filteredKeys = Object.keys(car).filter(key => key !== "year");
// Create a new object with the filtered keys
const filteredCar = {};
filteredKeys.forEach(key => {
filteredCar[key] = car[key];
});
// Print the filtered object
console.log(filteredCar);

You can also try this code with Online Javascript Compiler
Run Code
Output:
{ brand: "Toyota", model: "Corolla", color: "blue" }
In this example, we use `Object.keys()` to get the keys, `filter()` to exclude the `year` key, and then create a new object with the remaining keys.
Examples
Example 1: Basic Usage of Object.keys()
const student = {
name: "John",
age: 22,
course: "Computer Science"
};
const keys = Object.keys(student);
console.log(keys);

You can also try this code with Online Javascript Compiler
Run Code
Output:
["name", "age", "course"]
Explanation: The function returns an array containing all the property names of the student object.
Example 2: Using Object.keys() with an Empty Object
const emptyObj = {};
console.log(Object.keys(emptyObj));

You can also try this code with Online Javascript Compiler
Run Code
Output:
[]
Explanation: Since the object is empty, it returns an empty array.
Example 3: Iterating Over Object Keys
const car = {
brand: "Tesla",
model: "Model 3",
year: 2023
};
Object.keys(car).forEach(key => {
console.log(key + ": " + car[key]);
});

You can also try this code with Online Javascript Compiler
Run Code
Output:
brand: Tesla
model: Model 3
year: 2023
Explanation: This example loops through the keys and prints both the keys and their corresponding values.
Example 4: Object.keys() with Nested Objects
const person = {
name: "Alice",
details: {
age: 25,
country: "USA"
}
};
console.log(Object.keys(person));
console.log(Object.keys(person.details));

You can also try this code with Online Javascript Compiler
Run Code
Output:
["name", "details"]
["age", "country"]
Explanation: The method only retrieves the first-level keys. To get nested keys, you must call Object.keys() separately on nested objects.
Applications
- Iterating through an object's properties: Object.keys() helps loop through an object’s keys for various operations.
- Filtering object properties: It can be used to select specific properties.
- Checking if an object has keys: If Object.keys(obj).length === 0, the object is empty.
- Converting objects into arrays: Helps convert object keys into an array for further processing.
Exceptions
- Non-Object Values: If a non-object value is passed, JavaScript converts it into an object before retrieving the keys.
Example:
console.log(Object.keys("Hello"));

You can also try this code with Online Javascript Compiler
Run Code
Output:
["0", "1", "2", "3", "4"]
Explanation: The string is converted into an array-like object with indices as keys.
- Prototype Properties Are Ignored: Object.keys() does not return inherited properties.
Example:
function Person() {
this.name = "John";
}
Person.prototype.age = 30;
const personObj = new Person();
console.log(Object.keys(personObj));

You can also try this code with Online Javascript Compiler
Run Code
Output:
["name"]
Explanation: The age property is inherited from the prototype and does not appear in the keys.
Supported Browsers
The Object.keys() method is supported in all modern browsers, including:
- Google Chrome
- Mozilla Firefox
- Safari
- Microsoft Edge
- Opera
- Internet Explorer 9+
Frequently Asked Questions
What does Object.keys() return if the object has no properties?
It returns an empty array ([]).
Can Object.keys() be used on arrays?
Yes, it returns the indices as an array of strings.
What is the difference between Object.keys() and Object.entries()?
Object.keys() returns an array of property names, whereas Object.entries() returns an array of key-value pairs. This helps in retrieving both keys and their corresponding values.
Conclusion
In this article, we explored the Object.keys() method in JavaScript, which returns an array of a given object's property names. It helps in iterating over an object's keys and working with its properties efficiently. Understanding Object.keys() allows developers to manipulate objects more effectively and write cleaner, optimized JavaScript code.