πŸš€ Frontend DSA 6 - 🧩 Flatten Deep Nested JavaScript Objects into Dot Notation ('a.b': 1 Style)

One common pattern in modern JavaScript development, especially when working with deeply nested APIs, configs, or JSON data, is flattening nested objects into a dot notation format like:

{
  'a.b': 1,
  'e.f.g': 2,
  'e.f.h': 3
}

In this article, we'll learn how to recursively flatten any JavaScript object into this structure using two simple solutions. πŸ’ͺ


πŸ“¦ Real-World Use Cases

  • πŸ“Š API data formatting for logging, analytics, or debugging
  • πŸ“„ Exporting configs to JSON/YAML files
  • πŸ§ͺ Making deeply nested data easily accessible for form builders or search filters

πŸ§ͺ Example Input

const SAMPLE_DATA = {
  a: { b: 1 },
  e: { f: { g: 2, h: 3 } }
};

Expected Output:

{
  'a.b': 1,
  'e.f.g': 2,
  'e.f.h': 3
}

βœ… Solution 1 – Using an Intermediate Array

This solution collects key-value pairs in an array first, then formats it into an object.

// βœ… Recursively extract keys and values into an array
function printData(obj, parentKeyName = '') {
  let result = [];
  
  for (let currentKey in obj) {
    const value = obj[currentKey];

    // Construct the full key using dot notation
    const fullKey = parentKeyName ? parentKeyName + '.' + currentKey : currentKey;

    if (typeof value === 'object' && value !== null) {
      // Recurse deeper if it's an object
      result = [...result, ...printData(value, fullKey)];
    } else {
      // Push the final flattened key-value pair
      result.push({ key: fullKey, value });
    }
  }

  return result;
}

// πŸ›  Convert the array into object format
function printDataFormatted(obj) {
  const flattenedArray = printData(obj, '');
  const finalResult = {};

  flattenedArray.forEach(item => {
    finalResult[item.key] = item.value;
  });

  return finalResult;
}

Problem Statement


🧠 JavaScript Notes

  • typeof value === 'object' && value !== null is a safer check to exclude null, which is also typeof "object" in JavaScript! πŸ˜…
  • Recursion helps traverse deeply nested keys.
  • This method gives flexibility if you want to manipulate the intermediate array.

βœ… Solution 2 – Direct Object Return (More Elegant)

This approach builds the result directly without intermediate steps.

function printData(obj, parentKeyName = '') {
  let result = {};

  for (let currentKey in obj) {
    const value = obj[currentKey];
    const fullKey = parentKeyName ? parentKeyName + '.' + currentKey : currentKey;

    if (typeof value === 'object' && value !== null) {
      // Merge recursively flattened sub-object
      result = {
        ...result,
        ...printData(value, fullKey)
      };
    } else {
      result[fullKey] = value;
    }
  }

  return result;
}

Code Block


πŸ§ͺ Sample Outputs

🧾 Example 1

const obj1 = {
  a: { b: 1 },
  e: { f: { g: 2, h: 3 } }
};


console.log(printDataFormatted(SAMPLE_DATA));
// Output: { 'a.b': 1, 'e.f.g': 2, 'e.f.h': 3 }

console.log(printData(obj1));
// Output: { 'a.b': 1, 'e.f.g': 2, 'e.f.h': 3 }

🧾 Example 2

const obj2 = {
  x: { y: 5 },
  z: { w: { u: 7, v: 8 } }
};

console.log(printData(obj2));
// Output: { 'x.y': 5, 'z.w.u': 7, 'z.w.v': 8 }

🧾 Example 3

const obj3 = {
  config: {
    theme: {
      dark: true,
      primary: '#000'
    },
    version: 3
  }
};

console.log(printData(obj3));
// Output: { 'config.theme.dark': true, 'config.theme.primary': '#000', 'config.version': 3 }

βœ… Summary

Both solutions solve the same problem using recursion β€” with a small difference in style:

FeatureSolution 1Solution 2
Uses Intermediate Array?βœ… Yes❌ No
Direct Key-Value Result?❌ Needs extra formattingβœ… Returns final result
ReadabilityπŸ‘Œ Great for beginners🧠 Clean & concise

πŸ’‘ Bonus Challenge

Can you modify this function to:

  • Ignore keys with null or undefined values? πŸ€”
  • Include array indices in paths like 'a.0.b'? πŸ”’

If you'd like to see solutions for that or turn this into a reusable npm package, feel free to ask! πŸ’¬


Hey there from LearnYard! πŸ‘‹

Glad to see you exploring the free content from our course! We’ve shared 10 valuable articles at no cost to help you get a real feel of what’s inside.

If you’ve found these helpful, we’d love to know! πŸ’¬
Share your thoughts or key takeaways on LinkedIn, Twitter, or Instagram β€” and don’t forget to tag Gourav Hammad & Mohammad Fraz. We’ll personally respond to your post!

Thanks for being part of the LearnYard journey. Keep learning, keep growing! πŸš€


Loved the free content? Want access to the full course β€” for free? πŸ’Έ

Share the course with your friends using your affiliate link (you’ll find it on your profile or home page), and earn 20% commission on each sale.

Just 4–5 sales and you’ll recover the full course price of your course πŸ”
So why wait? Start sharing, start earning, and unlock the rest of the course effortlessly! πŸ› οΈπŸ“ˆ


πŸ“š Keywords for SEO

  • JavaScript Flatten Nested Object Keys
  • Recursively Convert Nested Object to Dot Notation in JavaScript
  • JavaScript Object Key Formatter
  • Deep Object Traversal in JavaScript
  • Flatten JSON Object Using JavaScript
  • Dot Notation Converter in JS
  • Nested Object Key Mapping JavaScript
  • Convert Deep Object to Flat Object in JS
  • JavaScript Utility for Flattening Objects
  • Handling Nested Data Structures in JavaScript

πŸ“’ Hashtags for Visibility

#JavaScriptObjects #FlattenObjectJS #DotNotationJS #DeepTraversalJS
#WebDevelopment #LearnJavaScript #CodeNewbie #JSForBeginners
#JavaScriptTips #JSONFlattening #FunctionalProgrammingJS #FrontendMasters #ObjectManipulationJS #JSUtilityFunctions #TechLearning #RecursiveJS #CodingChallenges #JSInterviewPrep #FrontendInterviewPrep #FlatJSONJS