Aller au contenu principal

mergeDeepRight()

mergeDeepRight<T, U>(left, right): T & U

Recursively merges objects, with right values taking precedence.

remarque

Arrays are replaced, not merged.


Type Parameters

T: T extends AnyRecord

The type of the left object.

U: U extends AnyRecord

The type of the right object.


Parameters

left: T

The left object (fallback values).

right: U

The right object (takes precedence).


Returns: T & U

A new deeply merged object.


See Also

mergeDeepLeft


Since

2.0.0


Note

Symbol keys are included via Reflect.ownKeys.


Performance

O(n) time & space where n is total number of properties. Early returns for null/undefined/primitives/arrays. Uses spread operator for shallow copy.


Example

const left = { user: { name: 'John', age: 30 } };
const right = { user: { name: 'Jane', email: 'jane@example.com' } };

mergeDeepRight(left, right);
// => { user: { name: 'Jane', age: 30, email: 'jane@example.com' } }

// Arrays: right wins
mergeDeepRight({ items: [1, 2] }, { items: [3, 4] });
// => { items: [3, 4] }

Use Cases

Merge with override precedence 📌

Merge objects recursively where the second object (right) overrides the first. Essential for applying configuration overrides or patching state.

const finalConfig = mergeDeepRight(defaultConfig, userConfig);
// userConfig overrides defaults

Patch complex state

Apply a partial update to a deep state tree. Critical for reducer logic in state management.

const nextState = mergeDeepRight(currentState, {
ui: { sidebar: { isOpen: true } } // Only updates isOpen, preserves other ui props
});

Combine nested defaults

Merge layers of configuration where inner layers override outer ones.

const effective = mergeDeepRight(globalProps, localProps);