JS Machine Coding Questions — Implementations You Must Know
Flatten — object with dot paths (5.2)
- Nested plain objects only (values are not arrays). Output keys use dots: a.b.c → one string key.
- Gotcha: If a value is an array, this keeps it under 'a.b' as a single array (does not expand [0]). Use 5.3 when arrays must become part of the path.
1function flattenObjectDot(obj, prefix = "") {
2 const out = {};
3 for (const k of Object.keys(obj)) {
4 const path = prefix ? `${prefix}.${k}` : k;
5 const v = obj[k];
6 if (v !== null && typeof v === "object" && !Array.isArray(v)) {
7 Object.assign(out, flattenObjectDot(v, path));
8 } else {
9 out[path] = v;
10 }
11 }
12 return out;
13}
14
15flattenObjectDot({ a: { b: { c: 1 } }, q: 10 });
16// { "a.b.c": 1, q: 10 }