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.
Try it
Section titled “Try it”Import
Section titled “Import”import { flatten } from "1o1-utils";import { flatten } from "1o1-utils/flatten";Signature
Section titled “Signature”function flatten({ value, depth }: FlattenArrayParams): unknown[];function flatten({ value }: FlattenObjectParams): Record<string, unknown>;Parameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
value | unknown[] | Record<string, unknown> | Yes | The array or plain object to flatten |
depth | number | No | Max recursion depth for arrays (defaults to Infinity). Ignored for objects. |
Returns
Section titled “Returns”unknown[]whenvalueis an array — flattened todepth.Record<string, unknown>whenvalueis a plain object — flat record with dot-notation keys.
Examples
Section titled “Examples”// Arraysflatten({ value: [1, [2, [3, [4]]]] });// => [1, 2, 3, 4]
flatten({ value: [1, [2, [3]]], depth: 1 });// => [1, 2, [3]]
// Objectsflatten({ value: { a: { b: 1, c: { d: 2 } }, e: 3 } });// => { 'a.b': 1, 'a.c.d': 2, e: 3 }Edge Cases
Section titled “Edge Cases”- Throws if
valueis 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 —
flattendoes not deep-clone leaves. Mutating a leaf in the result mutates the original.
Also known as
Section titled “Also known as”flat, deep flatten, flatten object, dot notation, crush
Prompt suggestion
Section titled “Prompt suggestion”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