@nevware21/ts-utils
    Preparing search index...

    Function forEachOwnKeySafe

    • Calls the provided callbackFn once for each own enumerable key (string and symbol) in the supplied value, skipping keys that are considered unsafe (__proto__, constructor, prototype). The callback can stop iteration early by returning -1.

      This helper wraps forEachOwnKey with extra key filtering for safer assignment flows. Use this instead of forEachOwnKey whenever keys come from untrusted input (e.g. user-supplied objects, parsed JSON).

      Type Parameters

      • T

        The source type.

      Parameters

      • theObject: T

        The object-like value to iterate.

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

        Invoked for each safe own enumerable key.

      • OptionalthisArg: any

        [Optional] The this context for the callback. If omitted, null, or undefined, the iterated object is used as this.

      Returns void

      0.14.0

      // Safely copy properties from an untrusted source
      function safeMerge<T extends object>(target: T, source: any): T {
      forEachOwnKeySafe(source, (key, value) => {
      (target as any)[key] = value;
      });
      return target;
      }

      // Note: use Object.defineProperty so "__proto__" is a real own enumerable
      // property rather than being treated as prototype syntax by the JS engine.
      const src: any = { name: "Alice" };
      Object.defineProperty(src, "__proto__", { value: "attack", enumerable: true, configurable: true, writable: true });
      const result = safeMerge({}, src);
      // result.name === "Alice" (__proto__ was silently skipped)
      // Symbol keys are included but unsafe string keys are filtered
      const sym = Symbol("safe");
      // Note: use Object.defineProperty so "__proto__" is a real own enumerable
      // property rather than being treated as prototype syntax by the JS engine.
      const obj: any = { a: 1, [sym]: "ok" };
      Object.defineProperty(obj, "__proto__", { value: "bad", enumerable: true, configurable: true, writable: true });

      forEachOwnKeySafe(obj, (key, value) => {
      console.log(String(key), value);
      // "a" 1
      // "Symbol(safe)" "ok"
      // "__proto__" is never visited
      });
      // Stop iteration early by returning -1
      const obj = { a: 1, b: 2, c: 3 };
      forEachOwnKeySafe(obj, (key) => {
      console.log(key); // "a", "b"
      if (key === "b") {
      return -1; // stops here
      }
      });