How to Flatten JavaScript objects into a single-depth Object?

In JavaScript, flattening an object means converting a nested object structure into a single-depth object where all nested properties are brought to the top level with flattened key names.

What is Object Flattening?

Object flattening transforms a multi-level nested object into a flat structure. For example, an object like {a: 1, b: {c: 2, d: 3}} becomes {a: 1, "b.c": 2, "b.d": 3} or {a: 1, c: 2, d: 3} depending on the flattening strategy.

Method 1: Simple Flattening (Merging Properties)

This approach merges nested properties directly into the parent object:

<!DOCTYPE html>
<html>
<head>
   <title>Simple Object Flattening</title>
</head>
<body>
   <div id="result1">Original Object: </div>
   <div id="result2">Flattened Object: </div>
   <script>
      var obj = {
         "a": 1,
         "b": 2,
         "c": {
            "d": 3,
            "e": 4
         }
      };
      
      var flattened = {};
      for (var key in obj) {
         if (typeof obj[key] === "object" && obj[key] !== null) {
            for (var subKey in obj[key]) {
               flattened[subKey] = obj[key][subKey];
            }
         } else {
            flattened[key] = obj[key];
         }
      }
      
      document.getElementById("result1").innerHTML += JSON.stringify(obj);
      document.getElementById("result2").innerHTML += JSON.stringify(flattened);
   </script>
</body>
</html>
Original Object: {"a":1,"b":2,"c":{"d":3,"e":4}}
Flattened Object: {"a":1,"b":2,"d":3,"e":4}

Method 2: Dot Notation Flattening (Preserving Path)

This approach creates keys using dot notation to preserve the original structure path:

<!DOCTYPE html>
<html>
<head>
   <title>Dot Notation Flattening</title>
</head>
<body>
   <div id="output"></div>
   <script>
      function flattenWithDots(obj, prefix = '') {
         let flattened = {};
         
         for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
               let newKey = prefix ? prefix + '.' + key : key;
               
               if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
                  Object.assign(flattened, flattenWithDots(obj[key], newKey));
               } else {
                  flattened[newKey] = obj[key];
               }
            }
         }
         
         return flattened;
      }
      
      var nested = {
         name: "John",
         address: {
            street: "123 Main St",
            city: "New York",
            coordinates: {
               lat: 40.7128,
               lng: -74.0060
            }
         },
         age: 30
      };
      
      var result = flattenWithDots(nested);
      document.getElementById("output").innerHTML = "<pre>" + JSON.stringify(result, null, 2) + "</pre>";
   </script>
</body>
</html>
{
  "name": "John",
  "address.street": "123 Main St",
  "address.city": "New York",
  "address.coordinates.lat": 40.7128,
  "address.coordinates.lng": -74.006,
  "age": 30
}

Method 3: Recursive Flattening Function

A more robust solution that handles deeply nested objects:

function flattenObject(obj, separator = '.') {
    const flattened = {};
    
    function flatten(current, prop) {
        if (Object(current) !== current) {
            // Primitive value
            flattened[prop] = current;
        } else if (Array.isArray(current)) {
            // Array
            for (let i = 0; i < current.length; i++) {
                flatten(current[i], prop + separator + i);
            }
            if (current.length === 0) {
                flattened[prop] = [];
            }
        } else {
            // Object
            let isEmpty = true;
            for (let p in current) {
                isEmpty = false;
                flatten(current[p], prop ? prop + separator + p : p);
            }
            if (isEmpty && prop) {
                flattened[prop] = {};
            }
        }
    }
    
    flatten(obj, '');
    return flattened;
}

// Example usage
const complexObj = {
    user: {
        name: "Alice",
        profile: {
            age: 25,
            hobbies: ["reading", "coding"],
            address: {
                city: "Boston",
                zipcode: "02101"
            }
        }
    },
    active: true
};

const flattened = flattenObject(complexObj);
console.log(JSON.stringify(flattened, null, 2));
{
  "user.name": "Alice",
  "user.profile.age": 25,
  "user.profile.hobbies.0": "reading",
  "user.profile.hobbies.1": "coding",
  "user.profile.address.city": "Boston",
  "user.profile.address.zipcode": "02101",
  "active": true
}

Comparison of Methods

Method Preserves Paths Handles Deep Nesting Handles Arrays
Simple Merging No No - One level only No
Dot Notation Yes Yes No
Recursive Function Yes Yes Yes

Use Cases

Object flattening is useful for:

  • Database Operations: Converting nested JSON to flat table columns
  • Form Data: Processing nested form structures
  • API Responses: Simplifying complex nested API data
  • Configuration Files: Flattening nested configuration objects

Key Considerations

Potential Issues:

  • Key Conflicts: Nested properties might overwrite parent properties
  • Data Loss: Original structure hierarchy is lost
  • Type Handling: Need to handle null values, arrays, and special objects

Conclusion

Object flattening transforms nested structures into single-depth objects, making data easier to process in certain scenarios. Choose the appropriate method based on whether you need to preserve the original structure path and handle complex nested data types.

Updated on: 2026-03-15T23:19:00+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements