-
Notifications
You must be signed in to change notification settings - Fork 4.1k
[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
mamtawardhani
wants to merge
4
commits into
Codecademy:main
Choose a base branch
from
mamtawardhani:js-object-keys
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
140 changes: 123 additions & 17 deletions
140
content/javascript/concepts/objects/terms/keys/keys.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.