Write a function `flattenObject(obj)` that flattens a nested object using dot notation for keys.
Problem Statement
<p>Write a function <code>flattenObject(obj)</code> that flattens a nested object using dot notation for keys.</p>
Examples
Input: obj = { a: { b: { c: 1 } }, d: 2 }
Output: { "a.b.c": 1, d: 2 }
Explanation: Nested hierarchy converted to dot notation keys.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
Use recursion to traverse nested objects.
š” Hint 2:
Concatenate parent key and child key with a dot.
š” Hint 3:
If a value is an object (not null, not array), recurse. Otherwise assign to the flattened key.
Editorial & Approach
Problem Overview & Intuition
To solve Flatten Object, we consider the execution characteristics of JavaScript engines. Write a function `flattenObject(obj)` that flattens a nested object using dot notation for keys. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (use recursion to traverse nested objects).
- Implement Logic: Handle state and transformations efficiently (concatenate parent key and child key with a dot).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function flattenObject(obj, prefix = "", result = {}) {
for (const key of Object.keys(obj)) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === "object" && obj[key] !== null && !Array.isArray(obj[key])) {
flattenObject(obj[key], newKey, result);
} else {
result[newKey] = obj[key];
}
}
return result;
}
Complexity Analysis
Time Complexity
O(N) linear scan over input
Space Complexity
O(1) constant auxiliary space (or O(N) output)
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.