Skip to content

flattenRecord

flattenRecord(source, options?): Record<string, unknown>

Defined in: packages/core/src/object/flatten-record.ts:114

Collapse a nested record into a one-level one, naming each leaf by the delimiter-joined path that reached it.

A leaf is anything that is not a plain object — a Date, a Map, a class instance and, by default, an array are all copied across whole. So is an empty plain object, which has no entry to name and would otherwise vanish.

A key that contains the delimiter is not escaped. { "a.b": 1 } flattens to { "a.b": 1 }, exactly as { a: { b: 1 } } does, and unflattenRecord reads both back as { a: { b: 1 } } — the delimiter always wins over a literal occurrence of it. Two inputs colliding onto one output key leave the last one written, in Object.keys order. Pick a delimiter the keys cannot contain when the round trip has to hold.

Keys are written with setRecordEntry, so an input key named __proto__ becomes an own entry of the result instead of reaching the prototype setter.

Time is linear in the number of nodes visited, plus the cost of building the keys, which is the total length of the output’s keys. Memory is the output record plus one stack frame per level of nesting, so a record nested deeper than the engine’s stack overflows rather than degrading.

Readonly<Record<string, unknown>>

The record to flatten; it is not modified.

FlattenRecordOptions

Delimiter, array handling and depth cap.

Record<string, unknown>

A new one-level record.

flattenRecord({ key1: { keyA: "v" }, key2: { a: { b: 2 } } });
// { "key1.keyA": "v", "key2.a.b": 2 }
flattenRecord({ host: { tags: ["a", "b"] } });
// { "host.tags": ["a", "b"] } — an array is a leaf
flattenRecord({ a: { b: { c: 1 } } }, { delimiter: "/", maxDepth: 2 });
// { "a/b": { c: 1 } }
```;
## Throws
RangeError If the delimiter is empty or `maxDepth` is below 1.