• Calls the provided callbackFn function once for each key in an object. This is equivalent to arrForEach(Object.keys(theObject), callbackFn) or if not using the array helper Object.keys(theObject).forEach(callbackFn) except that this helper avoids creating a temporary array of the object keys before iterating over them and like the arrForEach helper you CAN stop or break the iteration by returning -1 from the callbackFn function.

    Note: This helper only iterates string (and numeric) keys (via for...in loop) and does NOT include enumerable symbol keys. If you need to iterate all keys including symbol, use forEachOwnKey or forEachOwnKeySafe instead.

    Caution: this helper does not filter unsafe keys like __proto__, constructor, or prototype. If your callback uses the returned key to assign directly to another object (for example target[key] = value), validate keys first (for example with isUnsafePropKey) or use objForEachKeySafe when iterating untrusted input.

    Type Parameters

    • T

      The object type

    Parameters

    • theObject: T

      The object to iterate over

    • callbackfn: ((key: string, value: T[keyof T]) => number | void)

      A function that accepts up to two arguments, the key name and the current value of the property represented by the key.

        • (key, value): number | void
        • Parameters

          • key: string
          • value: T[keyof T]

          Returns number | void

    • OptionalthisArg: any

      [Optional] An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, null or undefined the object will be used as the this value.

    Returns void

    // Basic iteration - only string keys
    const obj = { name: "Alice", age: 30 };
    objForEachKey(obj, (key, value) => {
    console.log(key, value); // name Alice, age 30
    });
    // Unsafe keys warning - use objForEachKeySafe for untrusted input
    // Note: use Object.defineProperty (not an object literal) so "__proto__" is
    // created as a normal own enumerable property rather than being treated
    // specially by the JS engine.
    const untrustedObj: any = { name: "Bob" };
    Object.defineProperty(untrustedObj, "__proto__", { value: "attack", enumerable: true, configurable: true, writable: true });
    objForEachKey(untrustedObj, (key, value) => {
    console.log(key, value); // name Bob, __proto__ attack (UNSAFE!)
    });

    // Safe iteration with objForEachKeySafe
    objForEachKeySafe(untrustedObj, (key, value) => {
    console.log(key, value); // name Bob (unsafe keys filtered)
    });
    • objForEachKeySafe for safe iteration that filters unsafe keys
    • forEachOwnKey for iteration that includes both string and symbol keys
    • forEachOwnKeySafe for safe iteration with both string and symbol keys