Explorer
JavaScript

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

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (use recursion to traverse nested objects).
  3. Implement Logic: Handle state and transformations efficiently (concatenate parent key and child key with a dot).
  4. 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.

Flatten Object

Medium

Write a function flattenObject(obj) that flattens a nested object using dot notation for keys.

Example Scenarios
1Example 1
Input: obj = { a: { b: { c: 1 } }, d: 2 }
Output: { "a.b.c": 1, d: 2 }
Explanation:

Nested hierarchy converted to dot notation keys.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"a":1,"b.c":2,"b.d.e":3,"f":4}