javascript 26 lines · 6 steps

Flattening nested objects into dotted paths

A recursive walk turns deeply nested objects and arrays into a flat map of dotted-and-bracketed key paths.

Explained by highlit
1function flatten(obj, prefix = '', result = {}) {
2 for (const [key, value] of Object.entries(obj)) {
3 const path = prefix ? `${prefix}.${key}` : key;
4 
5 if (Array.isArray(value)) {
6 value.forEach((item, index) => {
7 const indexed = `${path}[${index}]`;
8 if (item !== null && typeof item === 'object') {
9 flatten(item, indexed, result);
10 } else {
11 result[indexed] = item;
12 }
13 });
14 } else if (value !== null && typeof value === 'object') {
15 if (Object.keys(value).length === 0) {
16 result[path] = value;
17 } else {
18 flatten(value, path, result);
19 }
20 } else {
21 result[path] = value;
22 }
23 }
24 
25 return result;
26}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Passing an accumulator and a prefix through recursion lets you build compound keys without merging partial results.
  2. 2Distinguishing arrays, objects, and primitives is what makes a traversal handle real-world nested data correctly.
  3. 3Empty containers need explicit handling, or recursion silently drops them from the output.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Flattening nested objects into dotted paths — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code