JavaScriptMedium
Flatten a nested object
Flattening turns a nested object into a single-level object whose keys are paths ("user.address.city"); recurse into plain objects (and optionally arrays), building the key by joining the parent path with the current key, and stop at primitives, dates and other non-plain values.
Decisions to make (ask the interviewer)
- Separator:
.is common; use something else if keys can contain dots. - Arrays: index them (
"tags.0"), keep them as values, or use bracket notation ("tags[0]"). - Empty objects/arrays: drop them or keep
{}/[]as values so the structure can be restored. - Special objects (
Date,Map, class instances): treat as leaf values. - Depth limit and cycle detection for untrusted data.
The inverse: unflatten
Split each key on the separator and create intermediate objects (or arrays when the next segment is numeric) as needed. Round-tripping flatten → unflatten is a good test.
Where it is used
- Form libraries and validation errors keyed by field path (
"address.zip"). - Query strings and environment variables (
APP__DB__HOST). - Translations files (
"home.hero.title"). - Diffing objects and storing documents in flat key-value stores.
- Logging and analytics properties.
Complexity
O(n) over the total number of values; recursion depth equals nesting depth (use an explicit stack for extremely deep data).
Code example
js
1const isPlainObject = (v) => v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;23function flattenObject(obj, { separator = ".", flattenArrays = true } = {}, prefix = "", out = {}, seen = new WeakSet()) {4 if (seen.has(obj)) throw new TypeError("Circular reference");5 seen.add(obj);6 for (const [key, value] of Object.entries(obj)) {7 const path = prefix ? `${prefix}${separator}${key}` : key;8 const recurse = isPlainObject(value) || (flattenArrays && Array.isArray(value));9 if (recurse && Object.keys(value).length > 0) flattenObject(value, { separator, flattenArrays }, path, out, seen);10 else out[path] = value; // primitives, dates, empty objects/arrays11 }12 return out;13}1415function unflattenObject(flat, separator = ".") {16 const root = {};17 for (const [path, value] of Object.entries(flat)) {18 const keys = path.split(separator);19 let node = root;20 keys.forEach((key, i) => {21 if (i === keys.length - 1) node[key] = value;22 else node = node[key] ??= /^\d+$/.test(keys[i + 1]) ? [] : {}; // arrays for numeric segments23 });24 }25 return root;26}2728const profile = {29 user: { name: "Ada", address: { city: "London", zip: "N1" } },30 tags: ["admin", "editor"],31 created: new Date(0),32 prefs: {},33};3435const flat = flattenObject(profile);36console.log(flat);37// { "user.name": "Ada", "user.address.city": "London", "user.address.zip": "N1", "tags.0": "admin", "tags.1": "editor", created: Date, prefs: {} }3839console.log(Object.keys(flattenObject(profile, { flattenArrays: false })).includes("tags")); // true - arrays kept whole4041const restored = unflattenObject(flat);42console.log(JSON.stringify(restored) === JSON.stringify(profile)); // true - round trip works
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.