๐ 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 excludenull
, 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:
Feature | Solution 1 | Solution 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