How to unflatten an object with the paths for keys in JavaScript?

In JavaScript, unflattening an object means converting a flattened object (where nested properties are represented as dot-separated keys) back to its original nested structure. This is commonly needed when working with APIs, databases, or form data that store nested objects as flat key-value pairs.

What is a Flattened Object?

A flattened object has nested properties represented as string keys with dot notation:

// Flattened object
var flatObj = {
   "user.name": "John",
   "user.age": 30,
   "user.address.city": "New York",
   "user.address.zip": "10001"
};

Basic Unflattening Algorithm

The unflattening process splits each key by dots and creates nested objects:

<!DOCTYPE html>
<html>
<head>
   <title>Unflatten Object Example</title>
</head>
<body>
   <div id="result"></div>
   
   <script>
      function unflattenObject(flatObj) {
         var result = {};
         
         for (var key in flatObj) {
            var value = flatObj[key];
            var path = key.split(".");
            var current = result;
            
            // Navigate through the path, creating objects as needed
            for (var i = 0; i < path.length - 1; i++) {
               var part = path[i];
               current[part] = current[part] || {};
               current = current[part];
            }
            
            // Set the final value
            current[path[path.length - 1]] = value;
         }
         
         return result;
      }
      
      // Example usage
      var flatObj = {
         "user.name": "John",
         "user.age": 30,
         "user.address.city": "New York",
         "user.address.zip": "10001"
      };
      
      var unflattened = unflattenObject(flatObj);
      
      document.getElementById("result").innerHTML = 
         "<h3>Original Flat Object:</h3>" +
         "<pre>" + JSON.stringify(flatObj, null, 2) + "</pre>" +
         "<h3>Unflattened Object:</h3>" +
         "<pre>" + JSON.stringify(unflattened, null, 2) + "</pre>";
   </script>
</body>
</html>

Enhanced Version with Array Support

This version handles arrays by detecting numeric keys:

<!DOCTYPE html>
<html>
<head>
   <title>Advanced Unflatten Example</title>
</head>
<body>
   <div id="advanced-result"></div>
   
   <script>
      function unflattenWithArrays(flatObj) {
         var result = {};
         
         for (var key in flatObj) {
            var value = flatObj[key];
            var path = key.split(".");
            var current = result;
            
            for (var i = 0; i < path.length - 1; i++) {
               var part = path[i];
               var nextPart = path[i + 1];
               
               // Check if next part is numeric (array index)
               if (!isNaN(nextPart)) {
                  current[part] = current[part] || [];
               } else {
                  current[part] = current[part] || {};
               }
               
               current = current[part];
            }
            
            current[path[path.length - 1]] = value;
         }
         
         return result;
      }
      
      // Example with arrays
      var complexFlat = {
         "users.0.name": "Alice",
         "users.0.age": 25,
         "users.1.name": "Bob",
         "users.1.age": 30,
         "settings.theme": "dark"
      };
      
      var complexUnflattened = unflattenWithArrays(complexFlat);
      
      document.getElementById("advanced-result").innerHTML = 
         "<h3>Complex Flat Object:</h3>" +
         "<pre>" + JSON.stringify(complexFlat, null, 2) + "</pre>" +
         "<h3>Complex Unflattened:</h3>" +
         "<pre>" + JSON.stringify(complexUnflattened, null, 2) + "</pre>";
   </script>
</body>
</html>

Common Use Cases

Use Case Description
Form Data Converting flat form inputs to nested objects
API Responses Restructuring flattened data from databases
Configuration Converting dot-notation config to nested objects

Key Points

  • Split keys by delimiter (usually dot ".")
  • Create nested objects progressively
  • Handle arrays by detecting numeric keys
  • Preserve original values at leaf nodes

Conclusion

Unflattening objects is essential for converting flat key-value structures back to nested objects. Use the basic algorithm for simple cases, or the enhanced version when dealing with arrays and complex nested data.

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

520 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements