Question Bank
JavaScript Immutable Object Key Removal: Two Approaches Quiz
Difficulty: Easy
Two seeded approaches to remove an object key without mutation (spread + delete, reduce + filter), plus two companions on destructure-and-drop and a deep-clone caveat.
JavaScript Immutable Object Key Removal: Two Approaches Quiz
Two seeded approaches to remove an object key without mutation (spread + delete, reduce + filter), plus two companions on destructure-and-drop and a deep-clone caveat.
1,150 views
26
Implement removeItem(obj, key) that returns a NEW object with the given key removed and the original object untouched. Use reduce over Object.keys and skip the target key.
Examples
Example 1:
Input: { color: 'red', model: '1980', owner: 'john doe' }, 'owner'
Output: { color: 'red', model: '1980' }
Explanation: A new object is returned; the original `owner` field is dropped, and the input object is unchanged.Implement removeItem(obj, key) using spread + delete on a shallow clone: const next = { ...obj }; delete next[key]; return next;. Why is this version safe even though delete is a mutating operation?
Examples
Example 1:
Input: { a: 1, b: 2, c: 3 }, 'b'
Output: { a: 1, c: 3 }
Explanation: A shallow clone is built first, then `delete` operates on the clone, leaving the original alone.Use destructure-and-rest to drop a key as a one-liner. What is the role of the throwaway underscore variable, and why is it the most idiomatic version?
Examples
Example 1:
Input: { a: 1, b: 2, c: 3 }, key = 'b'
Output: { a: 1, c: 3 }
Explanation: Destructuring pulls `b` into a discarded binding, and `...rest` collects everything else.Example 2:
Input: dropping a dynamic key
Output: same object minus the dynamic key
Explanation: The computed-property syntax `{ [key]: _, ...rest } = obj` lets the key name come from a variable.Caveat: spread + delete, destructuring-and-rest, and Object.keys.reduce all produce a SHALLOW clone. Show a case where dropping a key on a shallow clone unintentionally leaks a mutation through a nested object, and fix it with structuredClone.
Examples
Example 1:
Input: orig = { a: { count: 1 }, b: 2 }; const next = removeItem(orig, 'b'); next.a.count = 999;
Output: orig.a.count is now 999
Explanation: Shallow clone copies the reference to `a`, so writes through `next.a` reach `orig.a`.