Skip to main content

mergeObjects

mergeObjects is a utility function that deeply merges multiple objects into a target object.

Import

import { mergeObjects } from '@geodome/gdk/common';

Usage

const result = mergeObjects(target, source1, source2, ...);

Parameters

Parameters
  • target: any
    • The target object to merge into.
  • ...sources: any[]
    • One or more source objects to merge from.
Returns
  • any: The merged object.

Description

This function performs a deep merge of multiple objects into a target object. It recursively merges nested objects and overwrites primitive values and arrays.

Key features:

  • Handles nested objects
  • Overwrites arrays instead of merging them
  • Skips non-object sources
  • Preserves the target object's reference

Examples

Basic Usage

const target = { a: 1, b: { c: 2 } };
const source = { b: { d: 3 }, e: 4 };
const result = mergeObjects(target, source);
console.log(result);
// Output: { a: 1, b: { c: 2, d: 3 }, e: 4 }

Multiple Sources

const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };
const result = mergeObjects(target, source1, source2);
console.log(result);
// Output: { a: 1, b: 2, c: 3 }

Nested Objects

const target = { a: { b: 1, c: 2 } };
const source = { a: { c: 3, d: 4 } };
const result = mergeObjects(target, source);
console.log(result);
// Output: { a: { b: 1, c: 3, d: 4 } }
caution

This function uses any types for flexibility. Be cautious when using it with typed objects, as it may not preserve type information.