Sitelet https://github.com/pie6k/codablejson/blob/main/docs/src/content/json-serialization/copy.mdx
Skip to content

Latest commit

 

History

History
45 lines (33 loc) · 1.33 KB

File metadata and controls

45 lines (33 loc) · 1.33 KB

import { Callout } from 'nextra/components'

Copy

CodableJSON provides a copy function that creates deep copies of any nested, complex object while preserving all types and creating new references.

Basic Usage

import { copy } from "codablejson";

const original = {
  date: new Date("2025-01-01"),
  set: new Set(["a", "b", "c"]),
  map: new Map([["key", "value"]]),
};

const copied = copy(original);
// copied !== original (different object)
// copied.date instanceof Date === true
// copied.set instanceof Set === true
// copied.map instanceof Map === true

Reference Behavior

Every single object from the original data is copied. References are preserved inside the copy.

const shared = { value: "shared" };
const original = [shared, shared];

const copied = copy(original);
// copied[0] !== copied[1] (new references)
// copied[0] === copied[1] (reference equality is preserved inside the copy)
// original[0] !== copied[0] (reference equality is preserved **inside** the copy)
The `copy` function is equivalent to `decode(encode(value))`. Every reference in the copy will be new, ensuring complete independence from the original. You can copy anything that is serializable by CodableJSON, including custom types and circular references.