JS Machine Coding Questions — Implementations You Must Know
Flatten — object + array paths (5.3)
- Same as 5.2, but nested arrays become [index] segments in the key string (e.g. w[0].e.r).
- Mix of dots (object keys) and brackets (array indices) in one string.
- Three separate questions: 5.1 array flattening, 5.2 object-only dot paths, 5.3 object + array path keys.
1function flattenObject(obj, prefix = "") {
2 const out = {};
3 if (obj === null || typeof obj !== "object") {
4 if (prefix !== "") out[prefix] = obj;
5 return out;
6 }
7 if (Array.isArray(obj)) {
8 if (obj.length === 0) {
9 if (prefix !== "") out[prefix] = [];
10 return out;
11 }
12 obj.forEach((item, i) => {
13 const path = prefix ? `${prefix}[${i}]` : `[${i}]`;
14 Object.assign(out, flattenObject(item, path));
15 });
16 return out;
17 }
18 for (const k of Object.keys(obj)) {
19 const path = prefix ? `${prefix}.${k}` : k;
20 const v = obj[k];
21 if (v !== null && typeof v === "object") {
22 Object.assign(out, flattenObject(v, path));
23 } else {
24 out[path] = v;
25 }
26 }
27 return out;
28}
29
30flattenObject({ w: [{ e: { r: 8 } }], x: { y: 2 } });
31// { "w[0].e.r": 8, "x.y": 2 }