JavaScript Snippet

Flatten a Nested Data Object

Difficulty: Medium

Analytics events, form payloads, and config files often arrive as deeply nested objects, but databases, query strings, and CSV exporters want a flat key-value map. This snippet builds a recursive flattener that produces dot-path keys, extends it to handle arrays with bracket notation, and adds the inverse `unflatten` so the round-trip is lossless. Drop it next to your event tracker or form serializer.

Code Snippets
/

Flatten a Nested Data Object

Flatten a Nested Data Object

Analytics events, form payloads, and config files often arrive as deeply nested objects, but databases, query strings, and CSV exporters want a flat key-value map. This snippet builds a recursive flattener that produces dot-path keys, extends it to handle arrays with bracket notation, and adds the inverse `unflatten` so the round-trip is lossless. Drop it next to your event tracker or form serializer.

JavaScript
Medium
3 snippets
recursion
array-manipulation-patterns
js-spread-rest

1,087 views

16

The flattener walks every key, and when the value is a plain object it recurses with an extended prefix; otherwise it writes the leaf into out under the joined dot path. The accumulator out is threaded through so each recursive call appends to the same map, which avoids spreading dozens of intermediate objects on the way back up. The value !== null && typeof value === 'object' guard is critical because typeof null === 'object' in JavaScript, and a missed null check produces an infinite loop. This version intentionally treats arrays as leaves so the basic shape stays simple, accordion 2 lifts that restriction.