Skip to content

flatten

Flattens a nested object into a single-level object whose keys are the dot-notation path to each leaf value. The inverse of unflatten.

Only plain objects are recursed into — arrays, Date, Map, RegExp, class instances, and empty plain objects {} are kept as opaque leaf values. This keeps flatten/unflatten a clean, invertible pair: arrays can’t be losslessly told apart from plain objects once reduced to dotted keys, so this implementation doesn’t attempt it.

Caveat shared by every dotted-path flattening scheme: a key that itself contains a literal . is indistinguishable from real nesting once flattened ({ 'a.b': 1 } and { a: { b: 1 } } both produce { 'a.b': 1 }).

Available since v3.0.0

import { flatten } from '@helpers4/object';
// or, from the all-in-one package (same code, one install):
import { flatten } from 'helpers4/object';
flatten(obj: Record<string, unknown>): Record<string, unknown>
ParameterTypeDescription
objRecord<string, unknown>The object to flatten

Record<string, unknown> — A single-level object with dot-notation keys

Each key in the result is the full dot-notation path to a leaf value.

flatten({ server: { host: 'localhost', port: 8080 } })
// => { 'server.host': 'localhost', 'server.port': 8080 }

Arrays and special objects are kept as leaves

Section titled “Arrays and special objects are kept as leaves”

Only plain objects are recursed into — arrays stay intact.

flatten({ tags: ['a', 'b'], meta: { owner: 'x' } })
// => { tags: ['a', 'b'], 'meta.owner': 'x' }

View source on GitHub