Flatten Object Key Value
Recursively flattens a nested object structure into a single-level object while preserving leaf values.
Import
import { flattenObjectKeyValue } from 'nhb-toolbox';
Usage
Basic Usage
const nested = {
user: {
details: {
name: 'John',
age: 30
}
}
};
const flat = flattenObjectKeyValue(nested);
// Returns { name: 'John', age: 30 }
API Reference
Type Parameters
Name | Description |
---|---|
T | Type of input object |
Parameters
Name | Type | Description |
---|---|---|
object | T | Nested object to flatten |
Returns
T
: Flat object with all leaf values (type cast to input type)
Key Features
- Deep Flattening: Recursively processes nested objects
- Value Preservation: Maintains all terminal values
- Non-Destructive: Doesn't modify original object
- Simple Output: Single-level key-value structure
Examples
Simple Nesting
const obj = { a: 1, b: { c: 2, d: { e: 3 } } };
flattenObjectKeyValue(obj);
// { a: 1, c: 2, e: 3 }
Mixed Types
const data = {
meta: {
version: '1.0',
config: {
debug: true
}
},
items: ['a', 'b'] // Arrays remain untouched
};
flattenObjectKeyValue(data);
// { version: '1.0', debug: true, items: ['a', 'b'] }
Limitations
- Key Collisions: Nested objects may have duplicate keys that get overwritten
- Arrays: Treated as terminal values (not flattened)
- Type Information: Return type doesn't reflect flattened structure
- Circular References: May cause stack overflow for deeply nested objects and arrays
Type Definition
type GenericObject = Record<string, any>;
Recommended Use Cases
- Simplifying complex configurations
- Preparing data for key-value stores
- Redux state normalization
- Form data processing
- API response simplification
Kye differences from flattenObjectDotNotation
- Doesn't use dot notation - merges keys at root level
- More aggressive flattening (loses structural information)
- Better for cases where you only care about terminal values
- Simpler output format for certain use cases