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.
// 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)
});
Calls the provided
callbackFnfunction once for each key in an object. This is equivalent toarrForEach(Object.keys(theObject), callbackFn)or if not using the array helperObject.keys(theObject).forEach(callbackFn)except that this helper avoids creating a temporary array of the object keys before iterating over them and like thearrForEachhelper you CAN stop or break the iteration by returning -1 from thecallbackFnfunction.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, orprototype. If your callback uses the returned key to assign directly to another object (for exampletarget[key] = value), validate keys first (for example with isUnsafePropKey) or use objForEachKeySafe when iterating untrusted input.