Iterating
Objects
Learn how to loop through keys, values, and entries of JavaScript objects using built-in methods like Object.keys() and Object.entries().
What is a JavaScript Object?
An object is a collection of key-value pairs. Each key (also called a property name) maps to a value. Think of it like a dictionary: each word (key) has a definition (value).
Why Iterate Over Objects?
When you need to process every property in an object (display user settings, calculate totals, transform data), you need a way to loop through all key-value pairs systematically.
The Big Three Methods
JavaScript gives you three static methods on the Object constructor to extract data from any object:
Object.keys() Visualized
Object.values() Explained
Object.values() does the opposite of Object.keys(): it extracts only the values from each property, returning them as an array.
Object.entries() Explained
Object.entries() returns an array of [key, value] pairs. Each pair is itself a two-element array, giving you both pieces of information at once.
for...in vs Object Methods
JavaScript also has a for...in loop for iterating objects. But it behaves differently from Object.keys/values/entries in an important way.
| for...in | Object.keys/values/entries | |
|---|---|---|
| Inherited properties | ✕ Includes them | ✓ Own properties only |
| Returns | Keys one at a time | A full array |
| Array methods | ✕ Not chainable | ✓ .map(), .filter(), etc. |
| Recommended | Rarely | ✓ Preferred approach |
How to Iterate Step by Step
Example 1: Object.keys() + forEach
Print every key from a scores object:
english 88
science 92
Example 2: Object.entries() + Destructuring
Build a formatted string of all product details:
price: 999
inStock: true
Example 3: Transforming with .map()
Create an array of formatted labels from an object:
Filtering Object Properties
Combine Object.entries() with .filter() to select only the properties you need:
The Data Flow Pipeline
Common Mistakes
Summary Comparison
| Method | Returns | Best For | Example Output |
|---|---|---|---|
| Object.keys() | Array of strings | Listing property names | ["name", "age"] |
| Object.values() | Array of values | Summing, displaying | ["Alice", 16] |
| Object.entries() | Array of [k, v] | Transforming, filtering | [["name","Alice"], ["age", 16]] |
| for...in | Keys (one at a time) | Rarely recommended | Includes inherited |
Question 1 of 5
What does Object.keys() return?
Question 2 of 5
Given const obj = { a: 1, b: 2 }, what is the result of Object.entries(obj)?
Question 3 of 5
Why is obj[key] used instead of obj.key when iterating with a variable?
Question 4 of 5
What is one key disadvantage of using for...in compared to Object.keys()?
Question 5 of 5
Which code correctly logs every value in const pet = { name: "Rex", type: "dog" }?