To iterate over nested objects inside a plain JavaScript object, combine Object.entries() (or Object.keys() / Object.values()) with a recursive function that checks whether a property value is a non-null plain object (typeof val === "object" && val !== null && !Array.isArray(val)). That lets you walk arbitrary nesting depths, track key paths (like config.database.host), and process leaf values or nested objects cleanly.
1. Recursive Traversal with Object.entries() and Key Paths
Use Object.entries(obj) to read [key, value] pairs at each level and recurse whenever value is another plain object:
// Helper to check for non-null plain objects (excluding arrays)
function isPlainObject(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
// Recursively walk nested plain objects and collect leaf paths + values
function collectLeafEntries(obj, prefix = "", result = []) {
for (const [key, value] of Object.entries(obj)) {
const currentPath = prefix ? `${prefix}.${key}` : key;
if (isPlainObject(value)) {
collectLeafEntries(value, currentPath, result);
} else {
result.push({ path: currentPath, value });
}
}
return result;
}
const appConfig = {
app: { name: "ShopAPI", version: 2 },
db: { primary: { host: "localhost", port: 5432 } },
tags: ["prod", "v2"]
};
console.log(collectLeafEntries(appConfig));
Object.entries(obj): Iterates over own enumerable string-keyed properties as[key, value]pairs without pulling in inherited prototype properties.isPlainObject(value)guard: EnsuresnullorArrayvalues are not treated as nested plain objects.- Path tracking (
currentPath): Records dot-separated paths like"db.primary.host"so you know where each value lives.
2. Iterating One Level Deep vs. Transforming Nested Objects
If you only have a single nested layer (like a dictionary of user objects keyed by ID) or want to transform nested objects into a new structure without mutating the original:
// Iterate over a one-level map of nested objects or transform values immutably
function mapNestedObjectValues(obj, transformFn) {
const output = {};
for (const [key, value] of Object.entries(obj)) {
if (isPlainObject(value)) {
output[key] = mapNestedObjectValues(value, transformFn);
} else {
output[key] = transformFn(value, key);
}
}
return output;
}
const permissions = {
admin: { read: true, write: true },
viewer: { read: true, write: false }
};
const invertedFlags = mapNestedObjectValues(permissions, (val) =>
typeof val === "boolean" ? !val : val
);
console.log(invertedFlags);
- Immutable transformation: Building a new
outputobject preserves the original object untouched. - Single-level dictionary pattern: For
{ user1: { name: "Ali" }, user2: { name: "Sara" } }, a singlefor (const [id, profile] of Object.entries(users))loop is often simpler than recursion.
3. Common Traps to Avoid
Traversing nested objects in JavaScript trips up developers on type checks, prototype chains, and circular references:
- Using
typeof value === "object"alone: Bothnulland arrays ([]) havetypeof === "object", sonullthrows aTypeErroronObject.entries(null)and arrays get traversed like key-value maps unless filtered out. - Using
for...inwithoutObject.hasOwn()/Object.entries():for...inenumerates inherited prototype properties unless guarded, whereasObject.entries()only reads own enumerable properties. - Circular object references: If an object references itself or an ancestor (
a.self = a), naive recursion causes aRangeError: Maximum call stack size exceededunless tracked with aWeakSet.
TL;DR: Use Object.entries(obj) with a recursion helper guarded by a plain-object check (typeof val === "object" && val !== null && !Array.isArray(val)) to traverse nested objects of any depth cleanly.
Are you walking a fixed 2-level object structure, flattening nested keys into paths, or transforming nested values into a new object?
