Recurse with a path prefix. For each entry, if the value is an object, recurse with prefix.key; otherwise write the value under the joined path. Then decide the rules out loud, because that's what's being tested. Walk only plain objects and arrays (a Date or Map is a value). Write array items by index. Keep empty {} and [] as values so they aren't lost. Throw on cycles. For a strong finish, make it reversible: escape dots in keys, write indexes as a[0], and write an unsquash that defines properties rather than assigning them, so a "__proto__" key can't pollute prototypes.
Implement Squash Object — flatten a nested object into a single-level object with dot-separated keys.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Carry the path so far. Objects recurse and everything else is written at prefix.key. Arrays count as values here, and null is excluded explicitly because typeof null === 'object'. The result is a new object, and the input isn't changed.
// Nested objects become one level with dot-separated keys. Arrays and other values are leaves.function squash(obj, prefix = '', out = {}) {for (const [key, value] of Object.entries(obj)) {const path = prefix ? `${prefix}.${key}` : key;if (value !== null && typeof value === 'object' && !Array.isArray(value)) squash(value, path, out);else out[path] = value;}return out;}
passes 3 checks run on every build, against the native method where there is one
- nested objects become dot paths
- arrays, null and primitives are values
- the input isn't changed
Only plain objects (prototype Object.prototype or null) and arrays are walked. A Date, Map or class instance is written as a value, because flattening its fields would break it. Array items use their index as the key. Empty containers are written as values, otherwise { a: {} } would lose a entirely. A primitive root is rejected because it has no keys.
// Only plain objects and arrays are walked: a Date, Map or class instance is a value, not a// folder. Arrays use their indexes as keys. Empty containers are kept, so nothing is lost.const isPlain = (v) => v !== null && typeof v === 'object' && [Object.prototype, null].includes(Object.getPrototypeOf(v));const isContainer = (v) => Array.isArray(v) || isPlain(v);function squash(obj) {if (!isContainer(obj)) throw new TypeError('squash expects an object or array');const out = {};const visit = (node, path) => {const keys = isContainer(node) ? Object.keys(node) : null;if (path !== null && (!keys || keys.length === 0)) {out[path] = node; // a leaf, or an empty {} / []return;}for (const key of keys) visit(node[key], path === null ? key : `${path}.${key}`);};visit(obj, null);return out;}
passes 4 checks run on every build, against the native method where there is one
- arrays by index
- empty containers are kept
- Dates, Maps and class instances are values
- a root array works; a primitive root is rejected
With plain dot-joining, { 'a.b': 1 } and { a: { b: 1 } } squash to the same key. Escaping \ . [ ] in keys and writing indexes as [0] makes every path unambiguous, so unsquash rebuilds the input exactly (checked on 200 random objects, including awkward keys). unsquash uses defineProperty and own-property checks, so a path through __proto__ creates an ordinary key instead of polluting Object.prototype. A set of the objects on the current path catches cycles without rejecting shared references.
// Reversible: keys are escaped (\ . [ ]), array indexes are written a[0], so unsquash can// rebuild exactly what went in. Cycles are an error, not an endless loop.const isPlain = (v) => v !== null && typeof v === 'object' && [Object.prototype, null].includes(Object.getPrototypeOf(v));const escapeKey = (k) => k.replace(/[\\.[\]]/g, (c) => '\\' + c);function squash(obj) {if (!isPlain(obj)) throw new TypeError('squash expects a plain object');const out = {};const ancestors = new Set(); // objects on the current path; shared (non-circular) references are fineconst visit = (node, path) => {const array = Array.isArray(node);if (!array && !isPlain(node)) return void (out[path] = node);const keys = Object.keys(node);if (keys.length === 0 && path !== null) return void (out[path] = array ? [] : {});if (ancestors.has(node)) throw new TypeError(`circular reference at ${path}`);ancestors.add(node);for (const k of keys) {visit(node[k], array ? `${path}[${k}]` : path === null ? escapeKey(k) : `${path}.${escapeKey(k)}`);}ancestors.delete(node);};visit(obj, null);return out;}// 'a.b[0].c' -> ['a', 'b', 0, 'c']: key segments are strings, indexes are numbers.function parsePath(path) {let i = 0;const readKey = () => {let key = '';while (i < path.length && path[i] !== '.' && path[i] !== '[') {if (path[i] === '\\') i++;key += path[i++];}return key;};const segments = [readKey()];while (i < path.length) {if (path[i] === '.') {i++;segments.push(readKey());} else {const end = path.indexOf(']', i);segments.push(Number(path.slice(i + 1, end)));i = end + 1;}}return segments;}// Own properties are defined, never assigned, so a key like "__proto__" can't change a prototype.const define = (target, key, value) => Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });function unsquash(flat) {const root = {};for (const [path, value] of Object.entries(flat)) {const segments = parsePath(path);let node = root;segments.forEach((seg, j) => {if (j === segments.length - 1) return void define(node, seg, value);if (!Object.prototype.hasOwnProperty.call(node, seg)) define(node, seg, typeof segments[j + 1] === 'number' ? [] : {});node = node[seg];});}return root;}
passes 5 checks run on every build, against the native method where there is one
- readable paths
- keys with dots and brackets are escaped and round-trip
- round-trips 200 random objects
- __proto__ in the input never touches a prototype
- cycles throw; shared references are fine
Form libraries and query strings
Forms with nested fields name inputs address.city or items[0].qty, and libraries convert between those flat names and nested values, the same two functions as here.
Translation files and config
i18n catalogues and config systems often store nested keys flat (checkout.button.pay) and expand them at load time.
Prototype pollution
Unflattening untrusted paths with plain assignment is a well-known vulnerability: a key like __proto__.isAdmin changes every object in the program.
Forgetting
typeof null === 'object', then recursing intonull.Flattening
Dates and class instances into their fields.Empty objects and arrays silently disappearing.
Ambiguous output when keys contain dots.
Unsquashing with
obj[key] = value, which lets__proto__keys pollute prototypes.
How would you do it without recursion?
A stack of [node, path] pairs: pop one, write leaves, push children. Push them in reverse to keep the key order.
What about Symbol keys and non-enumerable properties?
Object.keys skips both. Reflect.ownKeys includes them, but symbols can't be joined into a string path, so most implementations leave them out.
What's the complexity?
O(total properties) time. The output keys can be long, so space is O(properties × depth) for the paths.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
- developer.mozilla.org/en-US/docs/Web/Security/Attacks/Prototype_pollution