Question
How can I loop through every property in a plain JavaScript object when the values are themselves objects?
For example, given this object:
const validation_messages = {
key_1: {
your_name: "jimmy",
your_msg: "hello world"
},
key_2: {
your_name: "billy",
your_msg: "foo equals bar"
}
};
How can I iterate over each top-level entry and access the nested values like your_name and your_msg for each one?
Short Answer
By the end of this page, you will understand how to loop through a JavaScript object whose properties contain other objects. You will learn the most common iteration techniques, how to access nested values safely, and which approach is best in real code.
Concept
In JavaScript, a plain object stores data as key-value pairs. Sometimes the value for each key is another object. This creates a structure often called an object of objects.
In your example, the top-level object has keys like key_1 and key_2. Each of those keys points to another object containing fields like your_name and your_msg.
To work with this structure, you usually:
- Loop through the top-level object
- Read each nested object
- Access the properties inside that nested object
This matters because many real programs use nested objects for:
- API responses
- configuration data
- form validation messages
- lookup tables
- grouped records by ID or name
A key thing to remember is that objects are not arrays. You do not loop through them with array indexes like obj[0], obj[1], and so on. Instead, you iterate over their property names using tools such as:
for...inObject.keys()Object.values()Object.entries()
For beginner-friendly and modern JavaScript, Object.entries() is often the clearest choice when you need both the key and the nested value object.
Mental Model
Think of a JavaScript object like a cabinet of labeled drawers.
- The outer object is the cabinet.
- Each top-level key such as
key_1orkey_2is a drawer label. - Inside each drawer is another small record card.
- That record card has fields like
your_nameandyour_msg.
Looping through the object means:
- Open each drawer
- Read the card inside
- Pull out the fields you need
So for key_1, you open the drawer labeled key_1, then read:
your_name→jimmyyour_msg→hello world
The same process repeats for every drawer in the cabinet.
Syntax and Examples
A common modern way to loop through an object of objects is Object.entries().
const validation_messages = {
key_1: {
your_name: "jimmy",
your_msg: "hello world"
},
key_2: {
your_name: "billy",
your_msg: "foo equals bar"
}
};
for (const [key, value] of Object.entries(validation_messages)) {
console.log(key); // key_1, key_2
console.log(value.your_name);
console.log(value.your_msg);
}
What this does
Object.entries(validation_messages)converts the object into an array of pairs.- Each pair looks like
[key, value]. keyis the top-level property name.valueis the nested object.
Example output
Step by Step Execution
Consider this code:
const validation_messages = {
key_1: {
your_name: "jimmy",
your_msg: "hello world"
},
key_2: {
your_name: "billy",
your_msg: "foo equals bar"
}
};
for (const [key, message] of Object.entries(validation_messages)) {
console.log(`Current key: ${key}`);
console.log(`Name: ${message.your_name}`);
console.log(`Message: ${message.your_msg}`);
}
Step by step
Object.entries(validation_messages)runs.- It produces an array like this:
[
["key_1", { your_name: "jimmy", your_msg: "hello world" }],
["key_2", { : , : }]
]
Real World Use Cases
Objects containing other objects appear often in real applications.
API response data
const usersById = {
u101: { name: "Ava", role: "admin" },
u102: { name: "Noah", role: "editor" }
};
You might loop through this to render user cards.
Validation errors by field
const errors = {
email: { message: "Email is required" },
password: { message: "Password is too short" }
};
You might iterate through this to show form errors.
Configuration groups
const config = {
database: { host: "localhost", port: 5432 },
cache: { enabled: true, ttl: 300 }
};
You might inspect or log settings when starting an app.
Real Codebase Usage
In real projects, developers often choose the object iteration method based on what they need.
1. Object.entries() for readable iteration
This is common when both the key and value matter.
for (const [id, user] of Object.entries(usersById)) {
console.log(id, user.name);
}
2. Object.values() when only values matter
This avoids unused variables.
const names = Object.values(usersById).map(user => user.name);
3. Guard clauses for missing nested data
Real data is not always complete.
for (const [key, item] of Object.entries(validation_messages)) {
if (!item) continue;
if (!item. || !item.) ;
.(item., item.);
}
Common Mistakes
Mistake 1: Treating an object like an array
Broken code:
for (let i = 0; i < validation_messages.length; i++) {
console.log(validation_messages[i]);
}
Why it fails:
- Plain objects do not have a
lengthproperty by default. - Their keys are not numeric indexes unless you explicitly use them that way.
Use this instead:
for (const [key, value] of Object.entries(validation_messages)) {
console.log(key, value);
}
Mistake 2: Accessing nested properties on the wrong object
Broken code:
for (const key in validation_messages) {
console.log(validation_messages.your_name);
}
Why it fails:
your_nameis not a property of the outer object.
Comparisons
| Approach | Best when | Gets key? | Gets value? | Notes |
|---|---|---|---|---|
for...in | You want classic object iteration | Yes | Yes, via obj[key] | May include inherited properties unless checked |
Object.keys() | You only need property names | Yes | Indirectly | Often used with for...of |
Object.values() | You only need the nested objects | No | Yes | Clean when keys are not needed |
Object.entries() |
Cheat Sheet
Loop through an object of objects
for (const [key, value] of Object.entries(obj)) {
console.log(key, value.someProperty);
}
Get only keys
Object.keys(obj)
Get only values
Object.values(obj)
Get keys and values
Object.entries(obj)
for...in pattern
for (const key in obj) {
if (Object.hasOwn(obj, key)) {
console.log(key, obj[key]);
}
}
Access nested properties
FAQ
How do I loop through a JavaScript object with nested objects?
Use Object.entries() or for...in to iterate over the top-level object, then access properties on each nested object.
for (const [key, value] of Object.entries(data)) {
console.log(value.your_name);
}
What is the best way to iterate over object properties in JavaScript?
For modern JavaScript, Object.entries() is usually the clearest when you need both keys and values.
Can I use map() directly on an object?
No. map() is an array method. Convert the object first with Object.keys(), Object.values(), or Object.entries().
Why does validation_messages.length not work?
Because plain objects do not have a built-in length property like arrays do.
What is the difference between and ?
Mini Project
Description
Build a small script that prints a contact directory stored as an object of objects. This demonstrates how to loop through top-level object keys and read nested properties from each entry.
Goal
Create a program that iterates through an object of contacts and prints each contact's ID, name, and message.
Requirements
- Create a plain JavaScript object with at least three top-level keys.
- Store an object as the value of each top-level key.
- Include
your_nameandyour_msginside each nested object. - Loop through all entries and print the key, name, and message.
- Skip any entry whose value is missing or null.
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.