Toolbox-XToolbox-X

Clone Object

Creates a deep clone of an object using structuredClone or deterministic JSON serialization.

cloneObject

The cloneObject function creates a deep clone of an object. By default, it uses the browser/runtime's built-in structuredClone API. It can also force deterministic JSON serialization.

Function Signature

function cloneObject<T extends GenericObject>(obj: T, serialize?: boolean): T

Parameters

  • obj (T): The object to clone.
  • serialize (boolean, optional): When true, forces deterministic JSON serialization with sorted keys. Defaults to false.

Return Value

  • T: A new object that is a deep clone of the input.

Example Usage

playground.ts

Behavior Details

  • Default Mode (serialize = false): Uses structuredClone if available. This preserves circular references, Date objects, Map, Set, RegExp, and Typed Arrays.
  • Serialization Mode (serialize = true): Uses stableStringify internally. All object keys are sorted alphabetically. undefined values are converted to null.
  • Safety Fallback: If both methods fail (e.g. circular references in JSON mode), it returns a shallow clone ({ ...obj }) instead of throwing an error.

Types

GenericObject

type GenericObject = Record<string, any>;

Last updated: Sun, Jun 14, 2026 07:06:16AM (UTC)

On this page