Skip to content

flatten

Flattens nested structures. For arrays, deep-flattens to a configurable depth (mirrors Array.prototype.flat). For plain objects, produces a flat record with dot-notation keys — the inverse of unflatten.

import { flatten } from "1o1-utils";
import { flatten } from "1o1-utils/flatten";
function flatten({ value, depth }: FlattenArrayParams): unknown[];
function flatten({ value }: FlattenObjectParams): Record<string, unknown>;
NameTypeRequiredDescription
valueunknown[] | Record<string, unknown>YesThe array or plain object to flatten
depthnumberNoMax recursion depth for arrays (defaults to Infinity). Ignored for objects.
  • unknown[] when value is an array — flattened to depth.
  • Record<string, unknown> when value is a plain object — flat record with dot-notation keys.
// Arrays
flatten({ value: [1, [2, [3, [4]]]] });
// => [1, 2, 3, 4]
flatten({ value: [1, [2, [3]]], depth: 1 });
// => [1, 2, [3]]
// Objects
flatten({ value: { a: { b: 1, c: { d: 2 } }, e: 3 } });
// => { 'a.b': 1, 'a.c.d': 2, e: 3 }
  • Throws if value is null, primitive, or anything other than an array or plain object.
  • Throws if a circular reference is detected during object flattening.
  • Only plain objects are descended into. Plain objects include Object.create(null). Arrays inside objects, Date, RegExp, Map, Set, and class instances are treated as leaves.
  • Empty nested objects are kept as {} leaves ({ a: {} }{ a: {} }).
  • Unsafe key segments (__proto__, constructor, prototype) are skipped.
  • Leaf values are shared by reference with the input — flatten does not deep-clone leaves. Mutating a leaf in the result mutates the original.

flat, deep flatten, flatten object, dot notation, crush

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 flatten to convert a deeply nested config object into dot-notation keys for a flat env-style format