The object type
The object to iterate over
A function that accepts up to two arguments, the key name and the current value of the property represented by the key.
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.
// Safe iteration - unsafe keys are skipped
const untrustedObj: any = { name: "Alice", constructor: {} };
Object.defineProperty(untrustedObj, "__proto__", { value: "attack", enumerable: true, configurable: true, writable: true });
objForEachKeySafe(untrustedObj, (key, value) => {
console.log(key, value); // Only prints: name Alice
});
// Difference between objForEachKey variants:
const source = { name: "Alice", age: 30, [Symbol.for("id")]: 123 };
// objForEachKey - includes unsafe keys if present, no symbol keys
objForEachKey(source, (key, value) => {
console.log(key, value); // name Alice, age 30
});
// objForEachKeySafe - filters unsafe keys, no symbol keys
objForEachKeySafe(source, (key, value) => {
console.log(key, value); // name Alice, age 30 (same as above since no unsafe keys)
});
// forEachOwnKeySafe - filters unsafe keys, includes symbol keys
forEachOwnKeySafe(source, (key, value) => {
console.log(key, value); // name Alice, age 30, Symbol(id) 123
});
Calls the provided
callbackFnfunction once for each key in an object, filtering out unsafe keys like__proto__,constructor, andprototype. This is a safe wrapper around objForEachKey that validates keys before passing them to the callback.Like objForEachKey, this helper iterates only string keys (via for...in loop) and does NOT include enumerable symbol keys. If you need to iterate both string and symbol keys, use forEachOwnKeySafe instead.