Flatten nested object in JavaScript using recursion [JavaScript Interview]
Understand flattening nested objects in JavaScript using a recursive approach, which includes the recursive code, how to approach a recursive solution and a step-by-step explanation.
Anuj Sharma
Last Updated Jun 4, 2026
![Flatten nested object in JavaScript using recursion [JavaScript Interview]](/_next/image?url=https%3A%2F%2Ftwijvresuxjxyhisasvd.supabase.co%2Fstorage%2Fv1%2Fobject%2Fpublic%2Fblog-images%2F5bf882d3-0967-44f5-bb29-5f33706cdfa6%2Fflatten-nested-object-in-javascript-using-recursion-javascript-interview-1771652199368.png&w=3840&q=75&dpl=dpl_aELrW6V6H921dC1fR61oHhmBkQxS)
When working with nested objects in JavaScript, there might be scenarios where you need to flatten the object to a single level to perform other operations on that flattened object.
In this blog post, we will explore how to flatten a nested object using a recursive approach. We will cover the recursive code, how to approach and provide step-by-step explanations.
Flatten nested object in JavaScript using recursion
Let's explore flattening nested objects in JavaScript using a recursive approach, accompanied by code and an explanation.
Recursive Approach to Flatten Nested Object
Flattening a nested object involves converting a nested structure into a flat structure where all nested properties are combined into a single-level object. To achieve this, we can use a recursive function to iterate through the nested object and flatten it.
Recursive Code Example
When approaching a recursive solution to flatten a nested object, consider the following steps:
- Start with a base case: Check if the current key in the object is a primitive type (number, string). If it is, add it to the flattened object.
- Check for object: If the current key is an object, recursively call the flatten function on that object.
- Combine with existing Object: Combine the flattened object with the current key and its value.
- Return the flattened object.
function flattenObject(obj) {
let flattened = {};
for (let key in obj) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
let flatObj = flattenObject(obj[key]);
for (let flatKey in flatObj) {
flattened[`${key}.${flatKey}`] = flatObj[flatKey];
}
} else {
flattened[key] = obj[key];
}
}
return flattened;
}
// Example object to flatten
const nestedObj = {
key1: 'value1',
key2: {
key3: 'value3',
key4: {
key5: 'value5'
}
}
};
const flattenedObj = flattenObject(nestedObj);
console.log(flattenedObj);
Step-by-Step Code Explanation
Let's walk through the step-by-step process of flattening a nested object using the provided code example:
- Define a function
flattenObjectthat takes an object as its parameter to flatten - Initialize an empty object
flattenedto store the flattened key-value pairs. - Iterate over each key in the object.
- If the value of the key is an object -> we recursively call
flattenObjecton that nested object. - We combine the flattened object with the current key and its value. If the key is nested, we concatenate the keys using dot notation.
- We return the
flattenedobject once all keys are processed.
Final thoughts
Flattening nested objects using recursion is a commonly asked JavaScript interview question and is also used in development. By understanding the recursive approach, writing efficient code, you can effectively flatten any nested object structure, and this even helps to understand the flattening of nested arrays as well.
Learn Next
A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me 🚀
Learn Next
Comments
Be the first to share your thoughts!
No comments yet.
Start the conversation!
Share your expertise
Publish a blog or quick notes on topics you know well — your write-up could be the answer someone needs before their next frontend interview.
Build your portfolio
Help the community
Sharpen your skills
Earn goodies
Other Related Blogs
Shallow Copy and Deep Copy in JavaScript - Object Cloning
Anuj Sharma
Last Updated Feb 21, 2026
Understand Shallow copy and Deep copy in JavaScript with detailed examples, and what is the difference between shallow copy vs deep copy in JavaScript.
How to convert HEX to RGB in JavaScript
Anuj Sharma
Last Updated Jul 6, 2026
A quick way to convert HEX to RGB in JavaScript that will help to do the CSS HEX to RGB color conversion programmatically.
How to convert RGB to HEX in JavaScript
Anuj Sharma
Last Updated Jul 6, 2026
A quick way to convert RGB to HEX in JavaScript that will help to do the CSS RGB to HEX color conversion programmatically
Understand Debouncing in JavaScript with Examples
Anuj Sharma
Last Updated Jun 27, 2026
Understand the concept of Debouncing in JavaScript to improve the performance of your web application and optimize the event handling in JavaScript, by limiting API calls or DOM events.
Implement JSON Parse polyfill in JavaScript
Anuj Sharma
Last Updated Jun 15, 2026
Explore the code implementation of JSON Parse Polyfill in JavaScript that can parse a string into valid JSON.
Implement JSON Stringify Polyfill in JavaScript
Anuj Sharma
Last Updated Jun 15, 2026
Explore the detailed explanation of the JSON Stringify Polyfill implementation in JavaScript to prepare for the frontend interviews.
What is javascript:void(0) and How it Works?
Anuj Sharma
Last Updated Jun 15, 2026
A comprehensive explanation about using javascript:void(0) in javascript. When to use javascript:void(0) and how it works with examples of using it with anchor tag.
Understand JavaScript Date Object with Examples (for JavaScript Interviews)
Anuj Sharma
Last Updated Jun 15, 2026
Go through different ways to display dates using javascript date object. It covers examples of date object usage to understand the main concepts of javascript date object.
