How do you loop through and enumerate all keys and values of a JavaScript object? | A1Lab@FahadM to JavaScriptEnglish • 6 days ago

How do you loop through and enumerate all keys and values of a JavaScript object?

message-square
0

To iterate over an object’s keys and values in JavaScript, Object.entries() with for...of is the clearest modern approach because it gives you [key, value] pairs for own enumerable string properties without walking up the prototype chain. For other property types—such as symbol keys, non-enumerable properties, or inherited properties—different iteration methods apply.


1. Own Enumerable String Keys and Values (Object.entries())

Use Object.entries(obj) inside a for...of loop when you want direct access to both each key and its value on the object itself:

const metrics = { latencyMs: 142, retries: 2, cached: true };

for (const [key, value] of Object.entries(metrics)) {
  console.log(`${key}:${value}`);
}

If you only need keys or only need values, Object.keys(obj) and Object.values(obj) avoid destructuring extra pairs:

const keys = Object.keys(metrics);     // ["latencyMs", "retries", "cached"]
const values = Object.values(metrics); // [142, 2, true]

2. Symbol Keys, Non-Enumerable Properties, and Prototype Chains

Different APIs expose different subsets of an object’s properties:

  • Reflect.ownKeys(obj): Returns all own keys on the object—including non-enumerable string keys and Symbol keys—but excludes inherited prototype properties:

    const secret = Symbol(“secret”); const config = { mode: “strict”, [secret]: “token-123” };

    for (const key of Reflect.ownKeys(config)) { console.log(String(key), config[key]); }

  • for...in: Loops over enumerable string keys from both the object and its prototype chain. Guard with Object.hasOwn(obj, key) if you only want own properties:

    for (const key in config) { if (Object.hasOwn(config, key)) { console.log(key, config[key]); } }

3. Common Traps to Avoid

  • Using for...in without Object.hasOwn(): Mutating or extending Object.prototype (or using objects with non-null prototypes) can introduce unexpected inherited keys into for...in loops.
  • Calling Object.entries() on null or undefined: Passing null or undefined throws a TypeError. Check obj != null && typeof obj === "object" first if inputs can be nullish.
  • Assuming Object.entries() is a deep traversal: It only visits top-level properties on that object; nested objects require recursive traversal if you need full tree enumeration.

TL;DR: Use for (const [key, value] of Object.entries(obj)) for clean iteration over own enumerable string properties, use Reflect.ownKeys(obj) when you need symbol or non-enumerable keys, and guard for...in loops with Object.hasOwn(obj, key).

Are you iterating over plain top-level dictionaries, objects with symbol/non-enumerable keys, or nested structures?