Flatten Object Dot Notation
Converts a nested object structure into a flat object using dot notation for keys.
Import
import { flattenObjectDotNotation } from 'nhb-toolbox';
Usage
Basic Usage
const nested = { user: { name: 'John', address: { city: 'NYC' } } };
const flat = flattenObjectDotNotation(nested);
// Returns { 'user.name': 'John', 'user.address.city': 'NYC' }
API Reference
Type Parameters
Name | Description |
---|---|
T | Type of input object |
Parameters
Name | Type | Description |
---|---|---|
object | T | Nested object to flatten |
Returns
GenericObject
: Flat object with dot-notation keys
Key Features
- Deep Flattening: Handles arbitrarily nested objects
- Dot Notation: Creates keys like 'parent.child.value'
- Type Safety: Maintains proper TypeScript typing
- Non-Destructive: Preserves original object
Examples
Simple Object
const obj = { a: 1, b: { c: 2 } };
flattenObjectDotNotation(obj);
// { 'a': 1, 'b.c': 2 }
Complex Nesting
const config = {
server: {
host: 'localhost',
ports: { http: 80, https: 443 }
}
};
flattenObjectDotNotation(config);
// {
// 'server.host': 'localhost',
// 'server.ports.http': 80,
// 'server.ports.https': 443
// }
Limitations
- Arrays: Will be treated as terminal values (not flattened)
- Special Objects: Date, RegExp etc. will be kept as-is
- Circular References: May cause stack overflow for deeply nested objects and arrays
- Key Collisions: Potential for duplicate keys in complex cases
Type Definition
type GenericObject = Record<string, any>;
Recommended Use Cases
- Configuration normalization
- API request/response transformation
- Database document flattening
- Object key path visualization