• Modifies an object by replacing each nested object that matches a specified Zod pattern with a new object returned by a callback function.

    Ignores the root object or array.

    *** Ignores any processing done by zod such as stripping away extra properties. ***

    Type Parameters

    • TValue extends object

      The type of the object to be processed.

    • TPattern extends ZodObject<ZodRawShape, UnknownKeysParam, ZodTypeAny, {}, {}>

      The Zod type representing the pattern for matching sub-objects.

    • TReturn extends Record<string, any>

      The type of the object returned by the callback function.

    Parameters

    • params: {
          fn: ((ctx) => TReturn);
          pattern: TPattern;
          shouldClone?: boolean;
          value: TValue;
      }

      The parameters for the function.

      • fn: ((ctx) => TReturn)
          • (ctx): TReturn
          • A callback function that is called for each matching sub-object and returns a new object to replace it.

            Parameters

            • ctx: Extract<ExtractObjectsDeep<TValue>, TypeOf<TPattern>> & Record<string, any>

            Returns TReturn

      • pattern: TPattern

        The Zod pattern used to match sub-objects within value.

      • Optional shouldClone?: boolean
      • value: TValue

        The object to be processed.

    Returns NoRootModification<TValue, TPattern, TReturn>

    • The modified object with each matching sub-object replaced by the new object returned by the callback function.

    Example

    // Example usage
    const obj = { a: { type: "match", data: 1 }, b: { data: 2 } }
    const pattern = z.object({ type: z.literal("match") })
    const result = replaceByPattern({
    value: obj,
    pattern,
    fn: (ctx) => ({ newData: ctx.data * 2 }),
    })
    console.log(result)
    // Output: { a: { newData: 2 }, b: { data: 2 } }

Generated using TypeDoc