Skip to content

[Edit] JavaScript: Objects: .keys() #7299

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 123 additions & 17 deletions content/javascript/concepts/objects/terms/keys/keys.md
Original file line number Diff line number Diff line change
@@ -1,47 +1,153 @@
---
Title: '.keys()'
Description: 'Extracts keys from an object and returns them as an array'
Description: "Returns an array of a given object’s own enumerable string-keyed property names."
Subjects:
- 'Web Development'
- 'Computer Science'
- 'Web Development'
Tags:
- 'Objects'
- 'Arrays'
- 'Methods'
- 'Objects'
- 'Properties'
CatalogContent:
- 'introduction-to-javascript'
- 'paths/front-end-engineer-career-path'
---

The `.keys()` static method extracts keys from an object and returns them as an array. It only returns the keys for the object's property and only for enumerable properties.
The **`Object.keys()`** JavaScript method returns an [array](https://www.codecademy.com/resources/docs/javascript/arrays) of a given [object's](https://www.codecademy.com/resources/docs/javascript/objects) own enumerable string-keyed property names. This static method extracts only the keys from an object, providing a convenient way to iterate over or analyze object properties without accessing their values.

> **Note:** The order of the keys in the resulting array is not guaranteed to be the same as the order in which they were defined in the object.

## Syntax

The basic syntax is:

```pseudo
Object.keys(obj)
```

- `obj`: An object from which the keys are extracted.
**Parameters:**

- `obj`: The object whose enumerable string-keyed property names are to be returned.

## Example
**Return value:**

Here's a simple example that extracts keys from an object and returns them as an array:
Returns an array of strings representing the given object's own enumerable string-keyed property keys.

## Example 1: Basic Usage of `Object.keys()`

This example demonstrates the fundamental usage of `Object.keys()` with a simple object containing different property types:

```js
const myObject = {
name: 'John',
age: 25,
city: 'London',
// Create a person object
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York',
};
const keysArray = Object.keys(myObject);
console.log(keysArray);

// Get all keys from the object
const keys = Object.keys(person);
console.log(keys);
```

The above example will give the following output:
This example results in the following output:

```shell
['name', 'age', 'city']
["firstName", "lastName", "age", "city"]
```

The method returns an array containing all enumerable property names from the object. The order of keys in the returned array matches the order in which they were defined in the object.

## Example 2: Using `Object.keys()` to iterate Over Object Properties

This example shows how to use `Object.keys()` to iterate through object properties, which is useful for processing or transforming object data:

```js
// Product inventory object
const inventory = {
laptops: 45,
smartphones: 123,
tablets: 67,
headphones: 89,
};

// Iterate through all product keys
Object.keys(inventory).forEach((product) => {
console.log(`${product}: ${inventory[product]} units`);
});

// Alternative: using for...of loop
for (const product of Object.keys(inventory)) {
if (inventory[product] < 50) {
console.log(`Low stock alert: ${product}`);
}
}
```

This example results in the following output:

```shell
laptops: 45 units
smartphones: 123 units
tablets: 67 units
headphones: 89 units
Low stock alert: laptops
```

## Codebyte Example: Filtering and Transforming Objects Using `Object.keys()`

This example demonstrates using `Object.keys()` to filter object properties and create new objects based on specific criteria:

```codebyte/javascript
// User settings object
const userSettings = {
theme: "dark",
notifications: true,
autoSave: false,
language: "en",
fontSize: 14,
showSidebar: true
};

// Filter only boolean settings
const booleanSettings = {};
Object.keys(userSettings).forEach(key => {
if (typeof userSettings[key] === 'boolean') {
booleanSettings[key] = userSettings[key];
}
});

console.log("Boolean settings:", booleanSettings);

// Create an array of setting names that are enabled
const enabledSettings = Object.keys(userSettings).filter(key =>
userSettings[key] === true
);

console.log("Enabled settings:", enabledSettings);
```

## Frequently Asked Questions

### 1. What is the difference between map keys and object keys?

In JavaScript:

- Object keys are always strings (or symbols). Even if you use a number or an object as a key, it gets converted to a string.
- Map keys can be of any type such as string, number, object, even functions. They're not converted to strings. This makes `Map` more flexible for key-value pairs where key type matters.

### 2. What is `Object.entries` and `Object.keys`?

- `Object.keys(obj)` returns an array of the keys (property names) in the object.
- `Object.entries(obj)` returns an array of [key, value] pairs from the object.

### 3. Can an object key be a number?

Not exactly. When you use a number as a key, JavaScript automatically converts it to a string.

### 4. Are object keys ordered?

Yes, in a specific way:
- Integer-like keys come first (sorted numerically).
- Then, string keys appear in insertion order.
- Symbol keys come last, also in insertion order.
Loading