Skip to content

unflatten

Builds a nested object from a flat record whose keys use dot notation. The inverse of flatten for objects. Optionally reconstructs arrays when key segments are all-numeric.

import { unflatten } from "1o1-utils";
import { unflatten } from "1o1-utils/unflatten";
function unflatten({ obj, arrays }: UnflattenParams): Record<string, unknown>
NameTypeRequiredDescription
objRecord<string, unknown>YesA flat record whose keys may contain . separators
arraysbooleanNoWhen true, all-numeric segments reconstruct as arrays (e.g. 'a.0', 'a.1'[...]). Default false.

Record<string, unknown> — A new nested object.

unflatten({ obj: { 'a.b': 1, 'a.c.d': 2, e: 3 } });
// => { a: { b: 1, c: { d: 2 } }, e: 3 }
// Array reconstruction
unflatten({ obj: { 'users.0.name': 'Ana', 'users.1.name': 'Bob' }, arrays: true });
// => { users: [{ name: 'Ana' }, { name: 'Bob' }] }
  • Throws if obj is not a plain object.
  • For conflicting keys (e.g. 'a': 1 and 'a.b': 2), last write wins. The input object is never mutated, even when a value at one key is itself an object that a later nested key descends into — unflatten shallow-clones any value it has to descend into.
  • Numeric segments stay as object string keys unless arrays: true.
  • With arrays: true, numeric segments longer than 7 digits fall back to object keys (sparse-array DoS guard).
  • Unsafe key segments (__proto__, constructor, prototype) are skipped — protects against prototype pollution.
  • Leaf values are shared by reference with the input — unflatten does not deep-clone leaves.

construct, expand, nest, deep set, dot notation, inverse flatten

I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use unflatten to convert a flat env-style config back into a nested object