Skip to main content

Merge And Flatten Objects

Deeply merges multiple objects and flattens the resulting structure using dot notation. Duplicate keys are resolved with last-in-wins behavior.

Import

import { mergeAndFlattenObjects } from 'nhb-toolbox';

Function Signature(s)

function mergeAndFlattenObjects<T extends GenericObject>(...objects: T[]): GenericObject

Usage

Basic Merging

const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };
const result = mergeAndFlattenObjects(obj1, obj2);
// Returns { 'a': 1, 'b.c': 2, 'b.d': 3, 'e': 4 }

API Reference

Type Parameters

NameDescription
TType of input objects

Parameters

NameTypeDescription
...objectsT[]Objects to merge (variadic)

Returns

GenericObject: Single merged object with dot-notation keys

Key Features

  1. Deep Merging: Combines multiple objects recursively
  2. Dot Notation: Flattens structure with nested keys
  3. Last-in Wins: Duplicate keys use last provided value
  4. Non-Destructive: Doesn't modify input objects

Examples

Multiple Object Merge

const defaults = { theme: { color: 'blue' } };
const userPrefs = { theme: { size: 'large' } };
const session = { theme: { color: 'red' } };

mergeAndFlattenObjects(defaults, userPrefs, session);
// {
// 'theme.color': 'red',
// 'theme.size': 'large'
// }

Conflict Resolution

const a = { settings: { timeout: 30 } };
const b = { settings: { timeout: 60 } };
mergeAndFlattenObjects(a, b);
// { 'settings.timeout': 60 }

Limitations

  1. Arrays: Treated as terminal values (not merged)
  2. Circular References: May cause stack overflow for deeply nested objects and arrays
  3. Type Information: Return type doesn't reflect flattened structure
  4. Special Objects: Date, Map, Set etc. treated as terminal values

Type Definition

type GenericObject = Record<string, any>;
  • Configuration merging
  • Deep object composition
  • Settings hierarchy resolution
  • API response consolidation
  • State management updates

Comparison with Similar Functions

FeaturemergeAndFlattenObjectsmergeObjects
Output StructureFlat (dot notation)Nested
Array HandlingOverwritesOverwrites
PerformanceSlower (flattening)Faster
Use CaseConfiguration stringsDeep merge