π 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 !== nullis 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