For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/object/merge.md.

merge es-toolkit

Deeply merges the source object into the target object, modifying the target object.

const result = merge(target, source);

Usage

merge(target, source)

Use merge when you want to deeply merge two objects. Nested objects and arrays are also merged recursively. Unlike toMerged, this function modifies the original target object.

import { merge } from 'es-toolkit/object';

// Basic object merging
const target = { a: 1, b: { x: 1, y: 2 } };
const source = { b: { y: 3, z: 4 }, c: 5 };
const result = merge(target, source);
// Both result and target become { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 }

// Arrays are also merged
const arrayTarget = { a: [1, 2], b: { x: 1 } };
const arraySource = { a: [3], b: { y: 2 } };
merge(arrayTarget, arraySource);
// arrayTarget becomes { a: [3, 2], b: { x: 1, y: 2 } }

// null values are handled appropriately
const nullTarget = { a: null };
const nullSource = { a: [1, 2, 3] };
merge(nullTarget, nullSource);
// nullTarget becomes { a: [1, 2, 3] }

undefined values do not overwrite existing values.

const target = { a: 1, b: 2 };
const source = { b: undefined, c: 3 };
merge(target, source);
// target becomes { a: 1, b: 2, c: 3 } (b is not overwritten)

Parameters

targetT extends Record<PropertyKey, any>required

The target object to merge the source object into. This object is modified.

sourceS extends Record<PropertyKey, any>required

The source object to merge into the target object.

Returns

Returns the target object with the source object merged in.

T & S

Examples

const target = { a: 1, b: { x: 1, y: 2 } };
const source = { b: { y: 3, z: 4 }, c: 5 };
const result = merge(target, source);
console.log(result);
// Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 }

const target = { a: [1, 2], b: { x: 1 } };
const source = { a: [3], b: { y: 2 } };
const result = merge(target, source);
console.log(result);
// Output: { a: [3, 2], b: { x: 1, y: 2 } }

const target = { a: null };
const source = { a: [1, 2, 3] };
const result = merge(target, source);
console.log(result);
// Output: { a: [1, 2, 3] }

Try It

::: sandpack

import { merge } from 'es-toolkit';

const target = { a: 1, b: { x: 1, y: 2 } };
const source = { b: { y: 3, z: 4 }, c: 5 };
const result = merge(target, source);
console.log(result);

:::

Source: es-toolkit

Re-exported verbatim from es-toolkit. Implementation, edge cases, and performance behavior are owned upstream. This page mirrors the documentation at the pinned version; the linked source is authoritative.