Skip to main content

Object

๐Ÿš€ 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