How do you iterate over nested objects inside a plain JavaScript object? | A1Lab@FahadM to JavaScriptEnglish • 5 days ago

How do you iterate over nested objects inside a plain JavaScript object?

message-square
0

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: Ensures null or Array values 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 output object preserves the original object untouched.
  • Single-level dictionary pattern: For { user1: { name: "Ali" }, user2: { name: "Sara" } }, a single for (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: Both null and arrays ([]) have typeof === "object", so null throws a TypeError on Object.entries(null) and arrays get traversed like key-value maps unless filtered out.
  • Using for...in without Object.hasOwn() / Object.entries(): for...in enumerates inherited prototype properties unless guarded, whereas Object.entries() only reads own enumerable properties.
  • Circular object references: If an object references itself or an ancestor (a.self = a), naive recursion causes a RangeError: Maximum call stack size exceeded unless tracked with a WeakSet.

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?