Blog/NotesConcept

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.

Intermediate

Anuj Sharma

Last Updated Oct 11, 2025


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

 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);     

Approaching a Recursive Solution

 

When approaching a recursive solution to flatten a nested object, consider the following steps:

  1. 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.
  2. Check for object: If the current key is an object, recursively call the flatten function on that object.
  3. Combine with existing Object: Combine the flattened object with the current key and its value.
  4. Return the flattened object.

Step-by-Step Code Explanation

Let's walk through the step-by-step process of flattening a nested object using the provided code example:

  1. Define a function flattenObject that takes an object as its parameter to flatten
  2. Initialize an empty object flattened to store the flattened key-value pairs.
  3. Iterate over each key in the object.
  4. If the value of the key is an object -> we recursively call flattenObject on that nested object.
  5. We combine the flattened object with the current key and its value. If the key is nested, we concatenate the keys using dot notation.
  6. We return the flattened object 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

  1. Most asked JavaScript questions for beginners.
  2. Promise polyfill in JavaScript
  3. Polyfill.all polyfill in JavaScript

Share this post now:

💬 Comments (0)

Login to comment

Advertisement

Flaunt You Expertise/Knowledge & Help your Peers

Sharing your knowledge will strengthen your expertise on topic. Consider writing a quick Blog/Notes to help frontend folks to ace Frontend Interviews.

Advertisement


Other Related Blogs

Understanding popstate event in Single Page Applications (SPAs)

Vijay Sai Krishna vsuri

Last Updated Aug 21, 2025

A Quick guide about popstate event in JavaScript, If you’ve ever hit the back button in your browser and wondered how your Single-Page Application knows which view to render, this guide is for you.

Master Hoisting in JavaScript with 5 Examples

Alok Kumar Giri

Last Updated Jun 2, 2025

Code snippet examples which will help to grasp the concept of Hoisting in JavaScript, with solutions to understand how it works behind the scene.

Polyfill for map, filter, and reduce in JavaScript

Anuj Sharma

Last Updated Oct 2, 2025

Explore Polyfill for map, filter and reduce array methods in JavaScript. A detailed explanation of Map, filter and reduce polyfills in JS helps you to know the internal working of these array methods.

setTimeout Polyfill in JavaScript - Detailed Explanation

Anuj Sharma

Last Updated Aug 3, 2025

Explore the implementation of setTimeout in JavaScript with a detailed explanation for every step. Understand all scenarios expected to implement the setTimeout polyfill.

How does JWT (JSON Web Token) Authentication work - Pros & Cons

Frontendgeek

Last Updated Sep 25, 2025

Understand the JWT(JSON Web Token) and how JWT decode works. It also covers how the end-to-end JWT authentication works between client & server, along with the pros and cons of using JWT.

Polyfill for Async Await in JavaScript - Step by Step Explanation

Anuj Sharma

Last Updated Oct 4, 2025

Understand polyfill for Async Await in JavaScript with a step-by-step explanation. This helps in understanding the internal functioning of Async Await in JavaScript.

Stay Updated

Subscribe to FrontendGeek Hub for the frontend interview preparation, interview experiences, curated resources and roadmaps.

FrontendGeek
FrontendGeek

© 2024 FrontendGeek. All rights reserved