These are the notes for JavaScript Coding Questions, episode 16, interview and placement practice for people who finished the SyntaxPilot JavaScript course. This is our second episode on objects, with three questions: invert an object (keys become values and values become keys), merge two nested objects deeply, and read a value deep inside an object from a path like "customer.address.city" without crashing when something is missing. On the way: why object keys are always strings, why spread is not a deep merge, a real security bug called prototype pollution, and the operators ?., ?? and ??=.
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Plain modern JavaScript, no packages.
Q1: Invert an object
Problem. Turn every key into a value and every value into a key. When two keys share a value, keep both.
{ chai: 10, coffee: 30, lassi: 30 } → { 10: ["chai"], 30: ["coffee", "lassi"] }
Real life: a chai stall's price list answers "what does chai cost?". The inverted list answers "what can I buy for 30 rupees?". Another one: your phone book goes from a name to a number; caller ID is the inverse, from a number to a name.
Think out loud
- Input: an object. Output: a new object whose keys are the old values.
- Edge cases: two keys with the same value (coffee and lassi both cost 30), an empty object, values that are not strings (numbers,
true, objects).
Attempt 1: the obvious loop
const prices = { chai: 10, coffee: 30, lassi: 30 };
const byPrice = {};
for (const key in prices) {
byPrice[prices[key]] = key;
}
console.log(byPrice);
console.log(Object.keys(byPrice));
{ '10': 'chai', '30': 'lassi' }
[ '10', '30' ]
Coffee is gone. An object holds only one value per key: coffee wrote 30 → "coffee", then lassi wrote 30 → "lassi" over it. No error, no warning, just lost data.
And look at the keys: '10' and '30' in quotes. Object keys are always strings (or symbols). A number used as a key is converted to a string, so o[1] and o["1"] are the same key:
const o = {}; o[1] = "a"; o["1"] = "b"; console.log(o);
{ '1': 'b' }
Fix: group the keys into arrays with ??=
const prices = { chai: 10, coffee: 30, lassi: 30 };
function invertAll(obj) {
const out = {};
for (const [key, value] of Object.entries(obj)) {
(out[value] ??= []).push(key);
}
return out;
}
console.log(invertAll(prices));
console.log(invertAll({}));
const flags = { veg: true, spicy: true, sweet: false };
console.log(invertAll(flags));
{ '10': [ 'chai' ], '30': [ 'coffee', 'lassi' ] }
{}
{ true: [ 'veg', 'spicy' ], false: [ 'sweet' ] }
Object.entries(obj)gives an array of[key, value]pairs, andconst [key, value]takes each pair apart (destructuring).a ??= bis the nullish assignment: ifaisnullorundefined, set it tob. The whole expression gives back the value ofaafterwards, so(out[value] ??= [])is "the array for this value, created if it is missing", and we push into it.- Like a family landline: one number, several names, so caller ID keeps a list of names.
Values that are objects: use a Map
const owners = { flatA: { id: 1 }, flatB: { id: 2 } };
const inv = {};
for (const [k, v] of Object.entries(owners)) inv[v] = k;
console.log(inv);
const m = new Map();
for (const [k, v] of Object.entries(owners)) m.set(v, k);
console.log(m.get(owners.flatA), m.size);
const simple = { a: "x", b: "y" };
console.log(Object.fromEntries(
Object.entries(simple).map(([k, v]) => [v, k])
));
{ '[object Object]': 'flatB' }
flatA 2
{ x: 'a', y: 'b' }
- An object turned into a string is
"[object Object]", so every object value becomes the same key, and flat A is overwritten. - A
Mapkeeps any value as a key, including the real object, som.get(owners.flatA)is"flatA"and the size is 2. - When every value is unique and a string, the one-liner is
Object.fromEntries(Object.entries(o).map(([k, v]) => [v, k])). It is not safe with duplicates:{ a: "x", b: "x" }gives{ x: 'b' }.
Complexity: one pass over n keys: O(n) time, O(n) space for the new object.
Q2: Merge two objects deeply
Problem. Combine an app's default settings with the settings one user saved. Nested objects are merged key by key, not replaced. The defaults must never change.
defaults: { theme: { color: "light", font: 16 }, lang: "en", tags: ["new"] }
saved: { theme: { font: 20 }, tags: ["pro"] }
result: { theme: { color: "light", font: 20 }, lang: "en", tags: ["pro"] }
Real life: a hostel's notice board has the common rules ("lights out at 11, guests until 8"). Room 12 gets one change ("guests until 9"). Room 12's rules are the common rules, section by section, with that one rule changed, written on a separate sheet, never on the notice board.
Think out loud
- Edge cases: arrays (merge or replace?), the defaults must stay unchanged for the next user, and settings that arrive as untrusted JSON from a request.
Attempt 1: spread
const defaults = {
theme: { color: "light", font: 16 }, lang: "en", tags: ["new"],
};
const saved = { theme: { font: 20 }, tags: ["pro"] };
const settings = { ...defaults, ...saved };
console.log(settings);
console.log(settings.theme.color);
{ theme: { font: 20 }, lang: 'en', tags: [ 'pro' ] }
undefined
Spread is shallow: it works one level deep. theme exists in both, so the whole saved theme object replaced the whole default one, and color was lost. Object.assign({}, defaults, saved) does exactly the same.
Attempt 2: a recursive merge that writes into the target
Recursion: a function that calls itself on a smaller part of the problem, here on the objects one level down.
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
function deepMerge(target, source) {
for (const key of Object.keys(source)) {
const both = isObj(target[key]) && isObj(source[key]);
if (both) deepMerge(target[key], source[key]);
else target[key] = source[key];
}
return target;
}
const defaults = {
theme: { color: "light", font: 16 }, lang: "en", tags: ["new"],
};
const asha = deepMerge(defaults, { theme: { font: 20 }, tags: ["pro"] });
console.log(asha);
const ravi = deepMerge(defaults, { lang: "hi" });
console.log(ravi.theme.font, defaults.theme.font, asha === defaults);
{ theme: { color: 'light', font: 20 }, lang: 'en', tags: [ 'pro' ] }
20 20 true
Asha's result is right, but Ravi gets font 20 too, the defaults now say 20, and asha is the defaults object. This version mutates (changes in place) its target. We passed the defaults as the target, so Asha's changes were written on the notice board itself.
isObj is the helper we need throughout: typeof null is "object" (episode 15), and an array is an object too, so we exclude both.
Fix: return a new object
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
function deepMerge(a, b) {
const out = { ...a };
for (const key of Object.keys(b)) {
const both = isObj(a[key]) && isObj(b[key]);
out[key] = both ? deepMerge(a[key], b[key]) : b[key];
}
return out;
}
const defaults = {
theme: { color: "light", font: 16 }, lang: "en", tags: ["new"],
};
const asha = deepMerge(defaults, { theme: { font: 20 }, tags: ["pro"] });
const ravi = deepMerge(defaults, { lang: "hi" });
console.log(asha);
console.log(ravi.theme.font, defaults.theme.font);
console.log(deepMerge({ a: 1 }, {}), deepMerge({}, { b: { c: 2 } }));
{ theme: { color: 'light', font: 20 }, lang: 'en', tags: [ 'pro' ] }
16 16
{ a: 1 } { b: { c: 2 } }
- Arrays are replaced, not merged by position (
tags: ['pro']). That is a choice most libraries make, because merging lists index by index gives strange results. A version that merges arrays is in the practice questions. - Values that exist only in
b(like{ c: 2 }above) are copied by reference. If you will change the result later,structuredClone(b)first.
The security trap: __proto__ and prototype pollution
Settings often arrive as JSON in a request body. JSON.parse happily creates a key named "__proto__":
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
function deepMerge(a, b) {
const out = { ...a };
for (const key of Object.keys(b)) {
const both = isObj(a[key]) && isObj(b[key]);
out[key] = both ? deepMerge(a[key], b[key]) : b[key];
}
return out;
}
const body = JSON.parse('{ "lang": "hi", "__proto__": { "isAdmin": true } }');
const r = deepMerge({ lang: "en" }, body);
console.log(r, r.isAdmin, ({}).isAdmin);
{ lang: 'hi' } true undefined
Nobody set isAdmin on r, yet r.isAdmin is true.
- Every object has a prototype: another object it inherits keys from.
out.__proto__ = valueis not a normal key write; it is a special setter that changesout's prototype. Sornow inheritsisAdmin: true. - With a merge that writes into its target (attempt 2), the same input reaches
Object.prototype, the prototype of every plain object, and then every object in the program saysisAdmin: true. This is called prototype pollution, and it has been a real bug in popular utility libraries.
Fix: skip the dangerous keys.
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const BLOCKED = new Set(["__proto__", "constructor", "prototype"]);
function deepMerge(a, b) {
const out = { ...a };
for (const key of Object.keys(b)) {
if (BLOCKED.has(key)) continue;
const both = isObj(a[key]) && isObj(b[key]);
out[key] = both ? deepMerge(a[key], b[key]) : b[key];
}
return out;
}
const body = JSON.parse('{ "lang": "hi", "__proto__": { "isAdmin": true } }');
const r = deepMerge({ lang: "en" }, body);
console.log(r, r.isAdmin);
{ lang: 'hi' } undefined
Other defences you will see in real code: building results with Object.create(null) (an object with no prototype at all), using a Map for user-controlled keys, and validating request bodies against a schema.
Complexity: every key of both objects is visited once: O(n) time, O(n) space for the new object, plus O(d) call-stack space for the nesting depth d.
Q3: Get a nested value by path
Problem. get(obj, path, fallback) returns the value at a path such as "customer.address.city". If any level is missing, return fallback instead of crashing. "items[0].name" must work too.
Real life: a postman reads an address line by line (state, city, street, house). If the street doesn't exist he doesn't crash: he stops, writes "address not found", and the letter goes back: "return to sender".
Think out loud
- Edge cases: a missing level in the middle, a real value of
0or""(must not be replaced by the fallback), array indexes written in brackets.
Attempts: obj[path], then split and walk
const order = {
id: 7, discount: 0,
customer: { name: "Asha", address: { city: "Pune", pin: 411001 } },
items: [{ name: "chai", qty: 2 }],
};
console.log(order.customer.address.city);
const path = "customer.address.city";
console.log(order[path]);
function get(obj, path) {
let cur = obj;
for (const key of path.split(".")) cur = cur[key];
return cur;
}
console.log(get(order, path));
console.log(get(order, "customer.phone.number"));
Pune
undefined
Pune
TypeError: Cannot read properties of undefined (reading 'number')
(The three lines are printed before the crash; the terminal also shows the stack trace under the TypeError.)
order[path]looks for one key literally named"customer.address.city". There is none.- Splitting at the dots works, but the customer has no
phone, so after two stepscurisundefined, and reading any key ofundefinedornullthrows.
Fix 1: optional chaining ?., with a fallback
const order = {
id: 7, discount: 0,
customer: { name: "Asha", address: { city: "Pune", pin: 411001 } },
items: [{ name: "chai", qty: 2 }],
};
function get(obj, path, fallback) {
let cur = obj;
for (const key of path.split(".")) cur = cur?.[key];
return cur || fallback;
}
console.log(get(order, "customer.address.city"));
console.log(get(order, "customer.phone.number", "no phone"));
console.log(get(order, "discount", "none"));
console.log(get(order, "items.0.name"), get(order, "items[0].name"));
Pune
no phone
none
chai undefined
- Optional chaining:
cur?.[key]means "ifcurisnullorundefined, stop and giveundefined; otherwise readcur[key]". Alsoa?.bandfn?.(). - Two new bugs: the discount is
0, but we got"none"; and"items[0].name"isundefined. ||returns the right side for every falsy value:0,"",false,NaN,null,undefined. A real discount of 0 was thrown away.split(".")leaves"items[0]"as one key, which doesn't exist.
Fix 2: ?? and a regex for brackets
const order = {
id: 7, discount: 0,
customer: { name: "Asha", address: { city: "Pune", pin: 411001 } },
items: [{ name: "chai", qty: 2 }],
};
function get(obj, path, fallback) {
const keys = path.replace(/\[(\d+)\]/g, ".$1").split(".");
let cur = obj;
for (const key of keys) cur = cur?.[key];
return cur ?? fallback;
}
console.log(get(order, "discount", "none"));
console.log(get(order, "items[0].name"), get(order, "items[5].name", "-"));
console.log(get(order, "customer.phone.number", "no phone"));
console.log(order.customer?.phone?.number ?? "no phone");
0
chai -
no phone
no phone
- Nullish coalescing
a ?? b:bonly whenaisnullorundefined.0 ?? 5is0,"" ?? 5is"". - The regex
/\[(\d+)\]/gfinds[, one or more digits (captured as group 1),], everywhere (g), and".$1"replaces each with a dot and the digits:"items[0].name"→"items.0.name". Array indexes are keys too ("0"), so the walk then works. - The last line is the same idea written directly in code when the path is known:
?.at each level that can be missing,??for the fallback.
Complexity: k = number of keys in the path. O(k) time, O(k) space for the keys array. The size of the object doesn't matter.
Complexity summary
| Question | Time | Space |
|---|---|---|
| Invert (group into arrays) | O(n) | O(n) |
| Invert into a Map | O(n) | O(n) |
| Deep merge (new object) | O(n), n = keys in both | O(n) + O(d) stack |
| Get by path | O(k), k = keys in the path | O(k) |
Common mistakes (and the exact outputs)
| Mistake | Code | What you see | Why | Fix |
|---|---|---|---|---|
| Plain invert loop | out[obj[key]] = key |
{ '10': 'chai', '30': 'lassi' } (coffee lost) |
one key holds one value | (out[v] ??= []).push(key) |
| Expecting number keys | Object.keys(byPrice) |
[ '10', '30' ] |
keys become strings | a Map if the type matters |
| Objects as keys | inv[v] = k with object v |
{ '[object Object]': 'flatB' } |
String(obj) is "[object Object]" |
new Map() |
fromEntries invert with duplicates |
{ a: "x", b: "x" } |
{ x: 'b' } |
later pairs overwrite | group into arrays |
| Spread as a deep merge | { ...defaults, ...saved } |
color is undefined |
spread is one level deep | recursive deepMerge |
| Merge into the defaults | deepMerge(defaults, saved) (mutating) |
20 20 true |
the target is changed | return a new object |
Copying __proto__ |
merge of JSON.parse('{"__proto__":...}') |
r.isAdmin is true |
out.__proto__ = sets the prototype |
skip __proto__, constructor, prototype |
| String path as one key | order["customer.address.city"] |
undefined |
no key with dots in its name | split and walk |
Walking without ?. |
cur = cur[key] |
TypeError: Cannot read properties of undefined (reading 'number') |
reading a key of undefined |
cur?.[key] |
|| for defaults |
return cur || fallback |
none for a discount of 0 |
0 is falsy |
?? |
| Brackets in a path | split(".") on "items[0].name" |
undefined |
"items[0]" isn't a key |
.replace(/\[(\d+)\]/g, ".$1") |
Mini project: a settings loader
Everything from today in one small, safe module: parse saved settings (bad JSON falls back to defaults), merge them over frozen defaults, and read values with a fallback.
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const BLOCKED = new Set(["__proto__", "constructor", "prototype"]);
function deepMerge(a, b) {
const out = { ...a };
for (const key of Object.keys(b)) {
if (BLOCKED.has(key)) continue;
const both = isObj(a[key]) && isObj(b[key]);
out[key] = both ? deepMerge(a[key], b[key]) : b[key];
}
return out;
}
function get(obj, path, fallback) {
const keys = path.replace(/\[(\d+)\]/g, ".$1").split(".");
let cur = obj;
for (const key of keys) cur = cur?.[key];
return cur ?? fallback;
}
const DEFAULTS = Object.freeze({ theme: { color: "light", font: 16 }, lang: "en", notify: { sms: true, email: false } });
function loadSettings(savedJson) {
let saved = {};
try { saved = JSON.parse(savedJson); } catch { console.log("bad JSON, using defaults"); }
return deepMerge(DEFAULTS, saved);
}
const s1 = loadSettings('{ "theme": { "font": 20 }, "notify": { "email": true } }');
console.log(get(s1, "theme.color"), get(s1, "theme.font"), get(s1, "notify.email"), get(s1, "notify.push", "off"));
const s2 = loadSettings("{ oops");
console.log(get(s2, "theme.font"), DEFAULTS.theme.font);
light 20 true off
bad JSON, using defaults
16 16
Object.freeze stops changes to the top level of DEFAULTS (episode 15's "deep freeze" exercise protects every level).
Your turn: set a value by path (solution)
Problem. set(obj, path, value) writes value at path, creating every missing level. Block __proto__ and friends.
const BLOCKED = new Set(["__proto__", "constructor", "prototype"]);
function set(obj, path, value) {
const keys = path.replace(/\[(\d+)\]/g, ".$1").split(".");
if (keys.some((k) => BLOCKED.has(k))) throw new Error("blocked key in path: " + path);
let cur = obj;
for (const key of keys.slice(0, -1)) {
if (cur[key] === null || typeof cur[key] !== "object") cur[key] = {};
cur = cur[key];
}
cur[keys.at(-1)] = value;
return obj;
}
const o = {};
set(o, "theme.dark.color", "black");
set(o, "theme.dark.size", 14);
console.log(JSON.stringify(o));
set(o, "theme", "light-only");
set(o, "theme.font", 16);
console.log(o);
try { set({}, "__proto__.isAdmin", true); } catch (e) { console.log(e.message); }
console.log(({}).isAdmin);
{"theme":{"dark":{"color":"black","size":14}}}
{ theme: { font: 16 } }
blocked key in path: __proto__.isAdmin
undefined
- Walk every key except the last (
keys.slice(0, -1)), creating{}where a level is missing or is not an object (a string like"light-only"can't hold keys, so it is replaced). Then assign the last key (keys.at(-1)). - The video's hint,
cur[key] ??= {}, creates missing levels; the extratypeofcheck also handles a level that exists but is a primitive. - Complexity: O(k) time and space for a path of
kkeys.
Practice questions (with solutions)
1. A deepMerge that also merges arrays (without duplicates).
Solution
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const BLOCKED = new Set(["__proto__", "constructor", "prototype"]);
function deepMerge(a, b) {
if (Array.isArray(a) && Array.isArray(b)) return [...new Set([...a, ...b])];
if (!isObj(a) || !isObj(b)) return b;
const out = { ...a };
for (const key of Object.keys(b)) {
if (BLOCKED.has(key)) continue;
out[key] = key in out ? deepMerge(a[key], b[key]) : b[key];
}
return out;
}
console.log(deepMerge({ tags: ["new", "veg"], n: 1 }, { tags: ["veg", "pro"], m: 2 }));
{ tags: [ 'new', 'veg', 'pro' ], n: 1, m: 2 }
Two arrays become their union (a Set removes the duplicate "veg"); two objects merge; anything else, b wins.
2. Flatten a nested object into dotted keys. { a: { b: 1 } } → { "a.b": 1 }.
Solution
function flatten(obj, prefix = "", out = {}) {
for (const [key, value] of Object.entries(obj)) {
const path = prefix ? `${prefix}.${key}` : key;
if (value !== null && typeof value === "object" && Object.keys(value).length > 0) flatten(value, path, out);
else out[path] = value;
}
return out;
}
console.log(flatten({ a: { b: 1, c: { d: 2 } }, e: [10, 20], f: null, g: {} }));
{ 'a.b': 1, 'a.c.d': 2, 'e.0': 10, 'e.1': 20, f: null, g: {} }
null and empty objects are kept as leaf values so nothing disappears. Every dotted key it produces can be read back with our get.
3. Invert a Map, grouping duplicate values.
Solution
function invertMap(map) {
const out = new Map();
for (const [key, value] of map) {
if (!out.has(value)) out.set(value, []);
out.get(value).push(key);
}
return out;
}
const seat = new Map([["Asha", 12], ["Ravi", 14], ["Neha", 12]]);
console.log(invertMap(seat));
Map(2) { 12 => [ 'Asha', 'Neha' ], 14 => [ 'Ravi' ] }
The keys stay numbers, because a Map never converts keys to strings.
4. Why does Object.keys({ 2: "x", 1: "y", b: 1, a: 2 }) not keep the written order?
Answer
[ '1', '2', 'b', 'a' ]
Keys that look like array indexes (non-negative integers) come first, in ascending order; then string keys in the order they were added. Another reason inverted "number keys" can surprise you.
Quick quiz
const cart = { items: 0, user: null };
console.log(cart.items || 5, cart.items ?? 5, cart.user?.name);
A) 5 5 undefined B) 0 0 null C) 5 0 undefined D) 5 0 TypeError
Answer
C, output 5 0 undefined. || replaces any falsy value, so 0 || 5 is 5. ?? replaces only null/undefined, so 0 ?? 5 is 0. user?.name stops at null and gives undefined, no TypeError.
Interview questions
- Why are object keys strings? Property keys are strings or symbols; anything else is converted with
String(). Use aMapwhen keys must keep their type or identity. - Shallow vs deep merge? Shallow (
{...a, ...b},Object.assign) replaces nested objects whole; deep merges them key by key, recursively. - Should a merge mutate its input? Usually not: shared defaults change for everyone. Return a new object (or document clearly that it mutates the target, like
Object.assign). - What is prototype pollution? Writing to
__proto__(orconstructor.prototype) through a merge, set-by-path or clone of untrusted input changes the prototype of objects, oftenObject.prototypeitself. Defend by skipping those keys,Object.create(null),Map, and validating input. ?.vs&&?a && a.balso stops on0or"";a?.bstops only onnull/undefined, and is shorter for deep chains.??vs||???keeps0,""andfalse;||replaces them. Mixing??with||or&&without parentheses is a SyntaxError.- How do lodash's
get/settreat"a[0].b"? They convert bracket indexes to keys, exactly like our regex, then walk the path.
Glossary
| Term | Meaning |
|---|---|
| Invert (an object) | Swap keys and values: the old values become keys |
| Key / value | The name of a property and what it holds: in { chai: 10 }, chai is the key, 10 the value |
Object.entries(o) |
An array of [key, value] pairs of o's own keys |
Object.fromEntries(pairs) |
Builds an object from [key, value] pairs |
| Destructuring | Taking a pair or object apart into variables: const [k, v] = pair |
??= (nullish assignment) |
a ??= b sets a to b only if a is null or undefined |
Map |
A key → value collection where keys can be any value (objects, numbers) and keep their type |
"[object Object]" |
What a plain object becomes when converted to a string |
| Shallow copy / merge | Only the top level is new; nested objects are shared |
| Deep merge | Merge nested objects key by key, at every level |
| Recursion | A function calling itself on a smaller part of the problem |
| Mutate | Change an existing object in place |
isObj (helper) |
Our check: not null, typeof "object", not an array |
| Prototype | The object another object inherits keys from |
__proto__ |
A special accessor that reads or sets an object's prototype |
| Prototype pollution | A bug where untrusted input changes a prototype, adding keys to many objects |
Object.create(null) |
An object with no prototype at all |
| Path | A string of keys joined by dots, like "customer.address.city" |
Optional chaining ?. |
a?.b gives undefined instead of throwing when a is null/undefined |
Nullish coalescing ?? |
a ?? b is b only when a is null/undefined |
| Falsy | Values that act as false: 0, "", false, NaN, null, undefined |
| Regex | A pattern for text; /\[(\d+)\]/g finds [digits] everywhere |
Capture group / $1 |
The part of a regex match in ( ), reused in the replacement as $1 |
Object.freeze |
Makes an object's top-level keys read-only |
| Fallback | The value returned when the real one is missing |
| Big-O | How the work grows with the input size: O(n) grows in step with n |
Summary
- To invert an object, collect keys into arrays per value with
(out[v] ??= []).push(key); object keys are always strings, so invert into aMapwhen the values are objects. - Spread is a one-level merge. A deep merge recurses into nested objects and should return a new object, never change the shared defaults.
- Merging untrusted JSON can copy a
__proto__key and pollute the prototype: skip__proto__,constructorandprototype. - To get by path, split the path (turning
[0]into.0), walk it with?., and use??for the fallback so0and""survive. - Next episode: closures: a counter factory,
once(fn),memoize(fn), and thevarloop trap.