CrackFrontendCF
Resources
Practice
CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❀️ by Tushar Khanna

CrackFrontendCF
Resources
Practice

πŸ“¦ Flatten Object Implementation

Converts nested objects into single-level structure with delimited keys. Useful for form serialization, API payloads, and configuration management.

Flattening an object converts a nested object structure into a single-level object where nested keys are joined with a delimiter (like underscore). This is commonly used for form data serialization, API payloads, and configuration management. -- βœ… Implementation -- πŸ§ͺ Example Usage -- πŸ” Output in Console -- 🧠 Notes Null-safe : Checks . Array-safe : Leaves arrays as-is. No global state : Uses as an accumulator. Prefix logic : Avoids leading underscores. -- <!-quiz-start --Q1: What does return? [ ] [x] [ ] [ ] Q2: How does the flatten function handle arrays? [ ] It flattens them with numeric indices [ ] It converts them to comma-separated strings [x] It leaves them as-is without recursing into them [ ] It throws an error Q3: Why is checked before recursing? [ ] Because null causes infinite loops [x] Because is 'object' but null should not be recursed into [ ] Because null values should be converted to undefined [ ] Because null cannot have properties <!-quiz-end --
JavaScriptUtilities
βž• Chained Sum (Curried Function)
medium
⏱️ Debounce Function in JavaScript
medium
πŸ“‹ Deep Clone Implementation
easy
πŸ”„ distinctUntilChanged() Polyfill
easy
πŸ“„ Document Comparison (Diff)
easy
πŸ“’ Custom EventEmitter Implementation
hard
πŸ“¦ Flatten Object Implementation
medium
🐫➑️🐍 Converting camelCase to snake_case in JavaScript (Without Regex)
easy
πŸ”„ mapLimit: Controlled Concurrency in JavaScript
medium
⚑️ Fire on Push: Dispatching Custom Events When an Array Changes in JavaScript
medium
πŸ”„ Removing Circular References from Objects
hard
πŸ“Š Sampling Function: Execute Once Every N Calls
medium
⏱️ Throttle Function in JavaScript
medium
πŸ”„ undefinedToNull Utility
medium
7 of 14
LibraryJavaScriptUtilities54 of 61

πŸ“¦ Flatten Object Implementation

jsutilsmedium

Flattening an object converts a nested object structure into a single-level object where nested keys are joined with a delimiter (like underscore). This is commonly used for form data serialization, API payloads, and configuration management.


βœ… Implementation

function flattenObject(obj, keyName = '', result = {}) {
  // Loop through all keys in the object
  Object.keys(obj).forEach(key => {
    // Construct new key path, joining with underscore if prefix exists
    const newKey = keyName ? `${keyName}_${key}` : key;

    const value = obj[key];

    // Debug: Log current key and value
    console.log(`🟑 Processing key: "${newKey}"`, value);

    if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
      // 🟠 Recurse into nested object
      console.log(`πŸ” Recursing into nested object at key: "${newKey}"`);
      flattenObject(value, newKey, result);
    } else {
      // βœ… Base case: assign value directly
      console.log(`βœ… Setting result["${newKey}"] =`, value);
      result[newKey] = value;
    }
  });

  // Debug: Show intermediate result at current level
  console.log('πŸ“¦ Current flattened result:', result);

  return result;
}

πŸ§ͺ Example Usage

const input = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 3
    }
  },
  f: null,
  g: [4, 5]
};

const flat = flattenObject(input);
console.log('βœ… Final Flattened Object:', flat);

πŸ” Output in Console

🟑 Processing key: "a" 1
βœ… Setting result["a"] = 1

🟑 Processing key: "b" { c: 2, d: { e: 3 } }
πŸ” Recursing into nested object at key: "b"

🟑 Processing key: "b_c" 2
βœ… Setting result["b_c"] = 2

🟑 Processing key: "b_d" { e: 3 }
πŸ” Recursing into nested object at key: "b_d"

🟑 Processing key: "b_d_e" 3
βœ… Setting result["b_d_e"] = 3

🟑 Processing key: "f" null
βœ… Setting result["f"] = null

🟑 Processing key: "g" [4, 5]
βœ… Setting result["g"] = [4, 5]

πŸ“¦ Current flattened result: {
  a: 1,
  b_c: 2,
  b_d_e: 3,
  f: null,
  g: [4, 5]
}

🧠 Notes

  • Null-safe : Checks value !== null.
  • Array-safe : Leaves arrays as-is.
  • No global state : Uses result as an accumulator.
  • Prefix logic : Avoids leading underscores.

Quick Quiz

Test your understanding with 3 quick questions

Q1What does `flattenObject({ a: { b: 1 } })` return?
Q2How does the flatten function handle arrays?
Q3Why is `value !== null` checked before recursing?

Continue Reading

CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❀️ by Tushar Khanna